5

可能重复:
默认构造函数和虚拟继承

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”变成了垃圾。关于如何处理它的任何想法?甚至可以使用参数化构造函数来解决菱形图案吗?

4

1 回答 1

2

看一下调用虚基类的重载构造函数,看起来如果继承是虚的,那么最派生的类必须调用基类的构造函数。

Problematic(int n, int n2, int n3, int n4) : Derived1(n, n2), Derived2(n, n3), Base(n), number(n4) {}
于 2013-01-23T01:47:19.213 回答