我可以存储指向前向声明类/结构的指针吗


#include <stdio.h>
struct B;
struct A {
B* b;
int num = 4;

A() {
b = new B(this);
}
};
struct A;
struct B {
A* a;
int num = 21;

B(A* a) {
this->a = a;
}

// function that does stuff with both A and B nums
int add() {
return num + a->num;
}
};
int main()
{
A thing;
printf("%d",thing.b->add());
return 0;
}

所以我的代码中有两个结构,其中结构B是结构A的成员。我只想让它们存储指向彼此的指针,这样它们就可以访问彼此的成员变量。这可能吗?我对重构建议持开放态度。

这是可能的,但您将不得不移动一些代码,因为在完全了解类型之前,许多表达式无法编译。例如,在B完全已知之前不能编译new B(this)

因此A构造函数需要在定义了B之后进行编译,就像这个一样

struct B;
struct A {
B* b;
int num = 4;

A();
};
struct B {
A* a;
int num = 21;

B(A* a) {
this->a = a;
}

// function that does stuff with both A and B nums
int add() {
return num + a->num;
}
};
inline A::A() {
b = new B(this);
}
int main()
{
A thing;
printf("%d",thing.b->add());
return 0;
}

最新更新