假设我正在编写一个链表,并且在我的头文件中有:
struct Node {
LIST_TYPE value;
Node* next;
Node* prev;
};
struct List{
int size;
Node* head;
Node* tail;
void (*list_print_function)(void*);
};
但是我不希望客户端能够看到Node结构。 static 修饰符是执行此操作的正确方法吗?关于静态结构的文档不多。
最佳答案
你想要的是一个不透明结构,你可以通过在你的头文件中声明struct
来做到这一点,这被称为前向声明但只在实现文件中定义它,就像你给出函数原型(prototype)但不给出定义一样。
然后您可以提供访问器函数以允许库用户使用struct
,一个示例
data-type.h
struct Struct;
void struct_set_value(struct Struct *struct, int value);
int struct_get_value(const struct Struct *const instance);
data-type.c
struct Struct
{
int value;
};
void struct_set_value(struct Struct *instance, int value)
{
instance->value = value;
}
int struct_get_value(const struct Struct *const instance)
{
return instance->value;
}
然后,您可以向库用户和编译对象提供 .h
文件,以便他们可以链接到它。
关于c - 用 C 辅助结构封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30039888/