如果class A
包含 aclass B
并且class B
还包含 aclass A
则否,则不能这样做。
class B; // forward declaration of name only. Compiler does not know how much
// space a B needs yet.
class A {
private:
B b; // fail because we don't know what a B is yet.
};
class B {
private:
A a;
};
即使这可行,也没有办法构造任何一个的实例。
B b; // allocates space for a B
// which needs to allocate space for its A
// which needs to allocate space for its B
// which needs to allocate space for its A
// on and on...
然而,它们可以包含彼此的指针(或引用)。
class B; // forward declaration tells the compiler to expect a B type.
class A {
private:
B* b; // only allocates space for a pointer which size is always
// known regardless of type.
};
class B {
private:
A* a;
};