c++ - 虚拟继承和参数化构造函数

标签 c++

<分区>

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

最佳答案

看看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) {}

关于c++ - 虚拟继承和参数化构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14471138/

相关文章:

c++ - 在scala中加载本地库时出错

c++ - 通过 == 比较 CString 和 TCHAR?

c++ - 内部和外部重载 C++ 运算符之间的区别

c++ - 选择重载引用接受函数

c++ - 增加IP地址

c++ - Google API CPP 客户端 - 使用服务帐户

c++ - QFile 打不开

c++ - 将数据插入文件中的特定位置而不覆盖c++

c++ - 包装 C++ 模板,以便它们可以在 C#、Java 等中使用

PHP Response 直接来自 C/C++ 语言