【问题标题】:cpp multiple inheritance unexpected ctor called [duplicate]cpp多重继承意外ctor称为[重复]
【发布时间】:2015-03-21 16:56:24
【问题描述】:

为什么Down没有通过LeftRight两次调用Base ctor?

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
}

【问题讨论】:

    标签: c++ constructor multiple-inheritance


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

      为什么要这样做?它实际上不是虚拟继承的全部意义,您已选择在代码示例中使用它。我猜你决定使用它而不研究它的作用。

      至于这种行为是“不正确的”,好吧,根据定义,你的期望是不正确的。

      【讨论】:

        猜你喜欢
        • 2012-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-30
        • 2015-04-28
        • 1970-01-01
        • 2019-09-26
        • 2014-12-31
        相关资源
        最近更新 更多