c++ - cpp 多重继承意外构造函数调用

标签 c++ constructor multiple-inheritance

<分区>

为什么 Down 不通过 LeftRight 两次调用 Base 构造函数?

class Base {
public:
    Base() { cout << "base-ctor" << endl; }
    Base(string a) { cout << a << endl; }
};

class Left : virtual public Base {
public:
    Left(string a) : Base(a) {}
};

class Right : virtual public Base {
public:
    Right(string a) : Base(a) {}
};

class Down : public Left, public Right {
public:
    Down(string a) : Left(a), Right(a) {}
};

int main() {
    Down x("down");
    // -> base-ctor
}

最佳答案

因为您正在使用基类的虚拟继承:

class Left : virtual public Base {
class Right : virtual public Base {

如果你想让它被调用两次,删除virtual关键字:

class Left : public Base {
class Right : public Base {

如果您想避免“菱形继承(钻石问题)”,这篇文章可能对您有用: http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem

关于c++ - cpp 多重继承意外构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29185398/

相关文章:

c++ - 将 QListView 缩减为列表中的公共(public)元素?

C++:比较两个字符串

c++ - C++调用抽象基类的构造函数

C++:结构/类中的构造函数与初始化列表

c++ - Qt程序部署

c++ - 如何找到谁在调用共享库函数?

c# - 在构造函数中抛出 ArgumentNullException?

c++ - 运行时检查失败 #0 - ESP 的值未在函数调用中正确保存

c++ - 如何覆盖多重继承中具有相同名称的基类的虚函数?

java - 了解多重继承和接口(interface)