2013-05-10 54 views
-8

下面的代碼:如何處理相互參照的類?

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' 
+1

這確實是非常基本的,我並不是想要表達自己的意思,但是你應該能夠通過一點點搜索來弄清楚這一點。 – 2013-05-10 22:04:45

+1

是的...那該怎麼辦? 'A myA; 「myA.b.a.b.a.b.a.b.a.b.a.b ...」 – mwerschy 2013-05-10 22:05:53

+1

http://en.wikipedia.org/wiki/Forward_Declaration – 2013-05-10 22:05:54

回答

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; 
}; 

現在類型B不包含A,它只是包含了指針A。它甚至不需要指向它的對象,所以我們打破了無限循環。

0

考慮到你要求類之間的引用,可能你來自Java,C#或類似的背景,其中只能將對象的引用放入其他對象中。

在C++中沒有這樣的限制:你可以讓一個對象的內容完全嵌套在另一個內部。但是爲了這個工作,你必須預先提供嵌套對象的定義。 C++需要這個定義才能計算外部對象的大小和佈局。爲了擺脫這種嵌套,您不需要將對象本身放置在外部對象內,而是將pointerreference放置在外部對象內部。

話雖這麼說,

// 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#。