虚拟继承和参数化构造函数

时间:2013-01-23 01:39:42

标签: c++

  

可能重复:
  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 个答案:

答案 0 :(得分: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) {}