C头文件循环
发布时间:2020-12-16 05:19:34 所属栏目:百科 来源:网络整理
导读:我有几个头文件,它归结为: tree.h中: #include "element.h"typedef struct tree_{ struct *tree_ first_child; struct *tree_ next_sibling; int tag; element *obj; ....} tree; 和element.h: #include "tree.h"typedef struct element_{ tree *tree_par
我有几个头文件,它归结为:
tree.h中: #include "element.h" typedef struct tree_ { struct *tree_ first_child; struct *tree_ next_sibling; int tag; element *obj; .... } tree; 和element.h: #include "tree.h" typedef struct element_ { tree *tree_parent; char *name; ... } element; 问题是它们都相互引用,所以需要包含tree需要的元素,要包含元素需要的树. 这不起作用,因为定义“树”结构,元素结构必须是已知的,但是要定义元素结构,必须知道树结构. 如何解决这些类型的循环(我认为这可能与’forward declaration’有关系?)? 解决方法
我认为这里的问题不在于失踪的包围守卫,而是两个结构在他们的定义中需要彼此的事实.所以这是一个类型定义汉和蛋问题.
在C或C中解决这些问题的方法是对类型进行远程声明.如果您告诉编译器该元素是某种结构,那么编译器就可以生成一个指向它的指针. 例如. 里面树 // tell the compiler that element is a structure typedef: typedef struct element_ element; typedef struct tree_ tree; struct tree_ { tree *first_child; tree *next_sibling; int tag; // now you can declare pointers to the structure. element *obj; }; 这样你就不必在tree.h里面加入element.h了. 你也应该把包围守卫放在你的头文件. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |