如何处理相互引用的类?

-8 c++ class

这是代码:

class B
{
    A a;
};

class A
{
    B b;
};

int main()
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是错误:

1>c:\mine\visual studio 2010 projects\myproj\compiled equivalent.cpp(7): 
  error C2079: 'B::a' uses undefined class 'A'
Run Code Online (Sandbox Code Playgroud)

Jos*_*eld 8

你不能.两个类不能作为成员相互包含.考虑回答一个问题"类型的大小是A多少?"那么A包含一个B,那么大小是B多少?那么B包含一个A,那么大小是A多少?哦,亲爱的,我们有一个无限循环.我们怎么可能将这个对象存储在有限的内存中?

也许更合适的结构是让其中一个类包含指向另一个类型的指针.在声明指针成员之前,指向的类型可以简单地向前声明:

class A; // A is only declared here, so it is an incomplete type

class B
{
    A* a; // Here it is okay for A to be an incomplete type
};

class A
{
    B b;
};
Run Code Online (Sandbox Code Playgroud)

现在,类型B不包含A,它只是包含一个指针A.甚至没有必要A指向它的对象,所以我们打破了无限循环.