2010-03-06 41 views
3

我在使用C++方面很新穎,而且我實際上已經停止了一個問題。對父類的引用

我有些類A,B,C定義如下(僞)

class A 
{ 
... 
    DoSomething(B par1); 
    DoSomething(C par1); 
... 
} 

class B 
{ 
    A parent; 
... 
} 

class C 
{ 
    A parent; 
... 
} 

的問題是:

如何使這個?如果我乾脆這樣做(正如我一直在C#中完成的那樣),它會給出錯誤。我非常理解這個原因。 (如果我將B和C的引用(包含)添加到它自己的頭文件中,則尚未聲明A)

任何解決此問題的方法? (使用void *指針不是邁向imho的方式)

+0

你想讓A成爲B和C的父類嗎? – 2010-03-06 14:30:42

+0

另一件事:你真的沒有一個*參考*在B和C的父母。如果你這樣做:'一個; B b(a); C c(a);'那麼會有三個不相關的A實例,而不是一個實例引用它的兩個對象。如果這是你想要的而是使用指向A的成員。 – UncleBens 2010-03-06 14:59:03

回答

5

Forward-declareBC。在達到A類的定義之前,編譯器會知道它們存在。

class B; 
class C; 

// At this point, B and C are incomplete types: 
// they exist, but their layout is not known. 
// You can declare them as function parameters, return type 
// and declare them as pointer and reference variables, but not normal variables. 
class A 
{ 
    .... 
} 

// Followed by the *definition* of B and C. 

PS

此外,另外一個技巧與問題無關的(看你怎麼算出來的一個C#背景):it's better to pass by const reference than by value

class A 
{ 
... 
    void DoSomething(const B& par1); 
    void DoSomething(const C& par1); 
... 
} 
1

使用向前聲明

您可以定義A類; A之前沒有它的實現,B和C之前,再後來把它定義

2

你應該轉發聲明B類及C:

class B; 
class C; 

class A { 
    ... 
}; 

點在哪裏B和C是A內引用,編譯器只需要知道這些是什麼樣的動物。使用前向聲明可以滿足編譯器的需求然後,你可以正確地定義它們。

+0

+1分類定義後的分號! – 2010-03-06 16:25:12

3

對於函數聲明,參數類型允許不完整如果函數沒有定義:

class B; 
class C; 

class A 
{ 
... 
    R DoSomething(B par1); 
    R DoSomething(C par1); 
... 
} 

class B 
{ 
    A parent; 
... 
} 

class C 
{ 
    A parent; 
... 
} 

inline R A::DoSomething(B par1) { ... } 
inline R A::DoSomething(C par1) { ... } 

所以你就BC成爲完成後,定義它們。但是,由於它們是在類之外定義的,因此要使它們成爲inline,以便不同翻譯單元中的多個定義不會導致鏈接器錯誤。

+0

也只是確保你真的想複製參數。根據你的需要,_maybe_通過引用傳遞它們,比如DoSomething(B&par1)將是最好的。 – rotoglup 2010-03-06 14:35:14