2013-01-23 61 views
5

可能重複:
Default constructor and virtual inheritance虛擬繼承和參數化的構造函數

class Base 
{ 
private: 
    int number; 
protected: 
    Base(int n) : number(n) {} 
public: 
    virtual void write() {cout << number;}  
}; 

class Derived1 : virtual public Base 
{ 
private: 
    int number; 
protected: 
    Derived1(int n, int n2) : Base(n), number(n2) {} 
public: 
    virtual void write() {Base::write(); cout << number;} 
}; 

class Derived2 : virtual public Base 
{ 
private: 
    int number; 
protected: 
    Derived2(int n, int n2) : Base(n), number(n2) {} 
public: 
    virtual void write() {Base::write(); cout << number;} 
}; 

class Problematic : public Derived1, public Derived2 
{ 
private: 
    int number; 
public: 
    Problematic(int n, int n2, int n3, int n4) : Derived1(n, n2), Derived2(n, n3), number(n4) {} 
    virtual void write() {Derived1::write(); Derived2::write(); cout << number;} 
}; 

int main() 
{ 
    Base* obj = new Problematic(1, 2, 3, 4); 
    obj->write(); 
} 

換句話說:

Base 
| \ 
| \ 
| \ 
| \ 
D1 D2 
| /
| /
|/
|/
Problematic 

我試圖得到「1 2 1 3 4「的輸出。但是,編譯器不斷抱怨我需要Base中的無參數構造函數,但是當我添加一個構造函數時,「1」變成垃圾。關於如何處理它的任何想法?使用參數化構造函數可以解決菱形圖案嗎?

+1

你錯過;「論派生類 – cppguy

+0

@cppguy - 我看不到它,但它不是真正的代碼反正(可能只是一個錯字)。 –

+0

@MaciejStachowski ildjarn爲你添加它 –

回答

2

看看Calling a virtual base class's overloaded constructor,看起來如果繼承是虛擬的,最派生類必須調用基類構造函數。

Problematic(int n, int n2, int n3, int n4) : Derived1(n, n2), Derived2(n, n3), Base(n), number(n4) {} 
+0

所以,這意味着所有從Derived1/2或它們的任何子類繼承的類都必須調用Base構造函數?我對C++的愛只是縮小了一點。 –