2013-01-23 11 views
5

Powiel możliwe:
Default constructor and virtual inheritancewirtualnej spadków i parametryzowane konstruktorzy

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

Innymi słowy:

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

Próbuję dostać „1 2 1 3 4 "na wyjściu. Kompilator jednak narzeka, że ​​potrzebuję konstruktora bez parametrów w Bazie, ale kiedy dodaję jeden, "1" zamienia się w śmieci. Jakieś pomysły, jak się do tego podejść? Czy możliwe jest nawet rozwiązanie wzoru diamentu za pomocą sparametryzowanego konstruktora?

+1

Brakuje; 's na klasach pochodnych – cppguy

+0

@cppguy - ja nie widzę, ale to nie jest prawdziwy kod mimo to (prawdopodobnie tylko literówka). –

+0

@MaciejStachowski ildjarn dodał go dla ciebie –

Odpowiedz

2

Spójrz na Calling a virtual base class's overloaded constructor, wygląda na to, że dziedziczenie jest wirtualne, najbardziej pochodna klasa musi wywołać konstruktor klasy podstawowej.

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

Oznacza to, że wszystkie klasy dziedziczące z Derived1/2 lub dowolnej z ich podklas muszą wywoływać Base constructor? Moja miłość do C++ właśnie się skurczyła. –