相互引用的结构
我想要两个可以相互包含的结构。这是一个例子:
struct a {
struct b bb;
};
struct b {
struct a aa;
};
但是这段代码无法编译。 gcc 说:
test.c:3: error: field ‘bb’ has incomplete type
有办法实现这一点吗?
I want to have two structs that can contain each other. Here is an example:
struct a {
struct b bb;
};
struct b {
struct a aa;
};
But this code doesn't compile. gcc says:
test.c:3: error: field ‘bb’ has incomplete type
Is there a way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那应该如何运作?
a
将包含b
,其中将包含a
,其中将包含b
等等...我想你想改用指针吗?
即使这是不好的编码风格 - 如果可能的话应该避免循环依赖。
How is that supposed to work?
a
would containb
, which would containa
, which would containb
, etc...I suppose you want to use a pointer instead?
Even that though is bad coding style - circular dependencies should be avoided if possible.
大多数头文件在定义其成员之前声明结构。结构定义将在其他地方定义。
Most of the header file declare the structure before defining its members. Structure definition will be defined in somewhere else.
处理这个问题的通常方法是使它们成为指针,然后动态分配它们,甚至只是从另一个结构的静态实例的地址分配指针。
不过,我建议您寻找树形结构的组织。也许这两个对象都可以指向共同的第三种类型。
The usual way of dealing with this is to make them pointers and then dynamically allocate them or even just assign the pointer from the address of a static instance of the other struct.
I would suggest, however, that you look for a tree-structured organization. Perhaps both objects could point to a common third type.
这是无稽之谈。
想象一下,如果您说每个
X
都包含一个Y
并且每个Y
都包含一个X
,那么在每个>X
是一个Y
,它又包含一个X
,后者又包含一个Y
,后者又包含一个 < code>X,无限。相反,您可以让
X
包含对Y
的引用或(或指向)Y
,反之亦然 -反之亦然。This is nonsensical.
Imagine if you say that every
X
contains aY
and everyY
contains anX
, then inside eachX
is aY
which in turn contains anX
, which in turn contains aY
, which in turn contains anX
, ad infinitum.Instead, you can have an
X
contain a reference to or (or pointer to) aY
and vice-versa.