Opaque Pointer / Incomplete Type

核心好处是 完全隐藏结构体内部实现,头文件只需要暴露 接口声明 + 类型名 + 操作方法,源文件才是真正定义接口和操作的文件,从而达到封装+解耦,是c语言模拟面向对象私有成员的核心写法。

  1. 因为头文件隐藏了接口的具体定义,所以外部代码无法直到结构体内部成员,只能使用头文件中的操作方法来操作结构体。
  2. 底层实现可以自由修改,也就是头文件对应的源文件可以自由修改
  3. 减少了头文件的依赖,加快编译速度
  4. 统一接口规范
  5. 代码解耦,独立性强
  6. 头文件中所操作的只能是结构体的指针,不能是结构体本身,因为头文件无法知道结构体具体定义

下面用一个例子来解释,写一个计算两个数的和的接口

sum.h

复制代码
#pragma once

typedef struct sum_t sum_t;

sum_t* sum_create(int a, int b);
int sum_get_result(sum_t* s);
void sum_destroy(sum_t* s);

sum.c

复制代码
#include "sum.h"
#include <stdlib.h>

struct sum_t {
    int a;
    int b;
};
sum_t* sum_create(int a, int b) {
    sum_t* s = (sum_t*)malloc(sizeof(sum_t));
    if (s) {
        s->a = a;
        s->b = b;
    }
    return s;
}
int sum_get_result(sum_t* s) {
    if (s) {
        return s->a + s->b;
    }
    return 0; // or handle error as appropriate
}
void sum_destroy(sum_t* s) {
    free(s);
}

main.c

复制代码
#include <stdio.h>
#include "sum.h"


int main(void) {
    sum_t* s = sum_create(3, 4);
    if (s) {
        int result = sum_get_result(s);
        printf("The sum is: %d\n", result);
        sum_destroy(s);
    } else {
        printf("Failed to create sum_t instance.\n");
    }
    return 0;
}
相关推荐
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
我不会插花弄玉1 天前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
西西弗Sisyphus1 天前
C++ explicit 关键字工程实践
开发语言·c++
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK1 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
上海潭龙东海科技有限公司2 天前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
一拳一个呆瓜2 天前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso2 天前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构