C递归头文件包含问题?
假设您必须在 2 个头文件中定义相关结构,如下所示:
ah content:
#include b.h
typedef struct A
{
B *b;
} A;
bh content:
#include a.h
typedef struct B
{
A *a;
} B;
在这种情况下,这种递归包含是一个问题,但 2 个结构必须指向其他结构,如何实现这一点?
Suppose you have to related structures defined in 2 header files like below:
a.h contents:
#include b.h
typedef struct A
{
B *b;
} A;
b.h contents:
#include a.h
typedef struct B
{
A *a;
} B;
In such this case, this recursive inclusion is a problem, but 2 structures must point to other structure, how to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要 #include ah 和 bh,只需前向声明 A 和 B。
ah:
bh:
您可能需要考虑这些类的耦合程度。如果它们耦合得非常紧密,那么它们可能属于同一个标头。
注意:您需要在
.c
文件中#include
ah 和 bh 来执行a->b->a
等操作代码>.Don't #include a.h and b.h, just forward-declare A and B.
a.h:
b.h:
You might want to think about how tightly coupled the classes are. If they're very tightly coupled, then maybe they belong in the same header.
Note: you'll need to
#include
both a.h and b.h in the.c
files to do things likea->b->a
.Google C/C++ 指南建议:
这意味着:
ahcontents:
bhcontents:
如果您更喜欢更安全的东西(但编译时间更长),您可以这样做:
ahcontents:
bhcontents:
Google C/C++ guidelines suggests:
That'd mean:
a.h contents:
b.h contents:
If you prefer something a bit safer (but longer to compile) you can do this:
a.h contents:
b.h contents:
您仅预先定义结构,这样您仍然可以声明指针:
在
ah
中:请注意我如何为
typedef
和 struct 标记使用单独的名称,以使有点清楚了。You pre-define the struct only, in that way you can still declare a pointer:
In
a.h
:Note how I use separate names for the
typedef
and struct tags, to make it a bit clearer.这会将其剪切为 C:
您可以根据需要重新排列
B
和A
。This will cut it in C:
You can rearrange
B
andA
as desired.