相互引用的结构 [英] Structs that refer to each other

查看:105
本文介绍了相互引用的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要有两个可以包含对方的结构。这里有一个例子:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
};

struct b {
struct a aa;
};

但是这段代码不能编译。 gcc说:

  test.c:3:error:field'bb'has incomplete type 

有没有办法实现这个功能?

解决方案

这应该如何工作? a 将包含 b ,其中包含 a ,其中会包含 b 等等...



我想你想用指针吗?

  struct b; 

struct a {
struct b * bb;
};

struct b {
struct a * aa;
};

尽管如此,编码风格却很糟糕 - 如果可能,应该避免循环依赖。

b $ b

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?

解决方案

How is that supposed to work? a would contain b, which would contain a, which would contain b, etc...

I suppose you want to use a pointer instead?

struct b;

struct a {
  struct b *bb;
};

struct b {
  struct a *aa;
};

Even that though is bad coding style - circular dependencies should be avoided if possible.

这篇关于相互引用的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆