下面的代码:如何处理相互参照的类?
class B
{
A a;
};
class A
{
B b;
};
int main()
{
return 0;
}
这里的错误:
1>c:\mine\visual studio 2010 projects\myproj\compiled equivalent.cpp(7):
error C2079: 'B::a' uses undefined class 'A'
下面的代码:如何处理相互参照的类?
class B
{
A a;
};
class A
{
B b;
};
int main()
{
return 0;
}
这里的错误:
1>c:\mine\visual studio 2010 projects\myproj\compiled equivalent.cpp(7):
error C2079: 'B::a' uses undefined class 'A'
你不能。两个类不能包含其他成员。考虑回答“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;
};
现在类型B
不包含A
,它只是包含了指针到A
。它甚至不需要指向它的对象,所以我们打破了无限循环。
考虑到你要求类之间的引用,可能你来自Java,C#或类似的背景,其中只能将对象的引用放入其他对象中。
在C++中没有这样的限制:你可以让一个对象的内容完全嵌套在另一个内部。但是为了这个工作,你必须预先提供嵌套对象的定义。 C++需要这个定义才能计算外部对象的大小和布局。为了摆脱这种嵌套,您不需要将对象本身放置在外部对象内,而是将pointer或reference放置在外部对象内部。
话虽这么说,
// C#
class A
{
int x;
B b;
}
class B
{
int y;
A a;
}
,如果你决定使用指针语法变得
// C++
class B; // tell the compiler that B is a class name
class A
{
int x;
B *pb; // the forward declaration above allows you to declare pointer to B here
};
class B
{
int y;
A *pa;
};
。
这是什么让是有事情,如:
// C++ again
class C
{
A a;
B b;
A *pa2;
};
具有内存布局形式:
C: 斧头a.pb 通过b.pa PA2
,这是不可能用Java/C#。
这确实是非常基本的,我并不是想要表达自己的意思,但是你应该能够通过一点点搜索来弄清楚这一点。 – 2013-05-10 22:04:45
是的...那该怎么办? 'A myA; “myA.b.a.b.a.b.a.b.a.b.a.b ...” – mwerschy 2013-05-10 22:05:53
http://en.wikipedia.org/wiki/Forward_Declaration – 2013-05-10 22:05:54