假设我在 list.h 中有这个:
typedef struct list_t list_t;
typedef struct list_iter_t list_iter_t;
list_iter_t iterator(list_t *list);
然后在list.c中定义它们:
typedef struct node_t {
...
} node_t;
struct list_iter_t {
node_t *current;
// this contains info on whether the iterator has reached the end, etc.
char danger;
};
struct list_t {
...
}
list_iter_t iterator(list_t *list) {
list_iter_t iter;
...
return iter;
}
除了在头文件中包含结构声明以便在某些文件 test.c 中我可以拥有:
#include "list.h"
void foo(list_t *list) {
list_iter_t = iterator(list);
...
}
比如以某种方式告诉编译器 list_iter_t 的存储大小?不得不使用指针很不方便(不是因为它是指针,而是其他原因),但同时我想尽可能隐藏实现细节。
最佳答案
简洁的答案是“否”。
告诉编译器struct
大小的方法是告诉它struct
的结构细节。如果要分配一个对象,而不是指向该对象的指针,编译器必须知道该对象的完整类型。如果类型不完整,您也无法通过指向结构的指针访问结构的成员。也就是说,编译器必须知道成员的偏移量和类型才能生成访问 someptr->member
的正确代码(以及分配 somevalue
或访问 somevalue.member
).
关于c - C 中有什么方法可以在头文件中转发声明结构而不必在其他文件中使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7278495/