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」變成垃圾。關於如何處理它的任何想法?使用參數化構造函數可以解決菱形圖案嗎?
你錯過;「論派生類 – cppguy
@cppguy - 我看不到它,但它不是真正的代碼反正(可能只是一個錯字)。 –
@MaciejStachowski ildjarn爲你添加它 –