c++ - 菱形继承(钻石问题)

标签 c++ multiple-inheritance diamond-problem

我正在研究菱形继承(钻石问题),并认为它适用于各种场景。这是我正在研究的其中之一。

#include <iostream> 
using namespace std;
class MainBase{

    public:
    int mainbase;
    MainBase(int i):mainbase(i){}
    void geta()
    {
        cout<<"mainbase"<<mainbase<<endl;
    }
};
class Derived1: public MainBase{

    public:
    int derived1;
    int mainbase;
    Derived1(int i):MainBase(i),derived1(i) {mainbase = 1;}
    public:
    void getderived1()
    {
        cout<<"derived1"<<derived1<<endl;
    }

};
class Derived2: public MainBase{

    public:
    int derived2;
    int mainbase;
    Derived2(int i):MainBase(i),derived2(i){mainbase = 2;}
    public:
    void getderived2()
    {
        cout<<"derived2"<<derived2<<endl;
    }
};
class Diamond: public Derived1, public Derived2{

    public:
    int diamond;
    int mainbase;
    Diamond(int i,int j, int x):Derived1(j),Derived2(x),diamond(i){mainbase=3;}
    public:
    void getdiamond()
    {
        cout<<"diamond"<<diamond<<endl;
    }
};
int main()
{
    Diamond d(4,5,6);
//    cout<< d.MainBase::mainbase;
    cout<<"tested"<<endl;
    cout<<d.mainbase;
    cout<<d.Derived2::mainbase<<endl;
    cout<<d.Derived1::mainbase<<endl;
    /*cout<<d.Derived2::MainBase::mainbase<<endl;
    cout<<d.Derived1::MainBase::mainbase<<endl;*/
}

我现在想知道如何访问 MainBase 类 mainbase 变量?任何输入。

最佳答案

你做你在那里做的事:

cout<<d.Derived2::MainBase::mainbase<<endl;
cout<<d.Derived1::MainBase::mainbase<<endl;

但是,它可能无法实现您想要实现的目标。也许,您应该使用 virtual 继承?你所拥有的意味着你的对象中将有两个 MainBase 成员拷贝,每个继承轨道一个。

(来自 MSDN)。

When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. A single copy of its data members is shared by all the base classes that use it as a virtual base.

可能这样的东西更适合你:

class Derived1: virtual public MainBase{

关于c++ - 菱形继承(钻石问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1264304/

相关文章:

c++ - 文件处理 C++ 时出错

c# - 如何在多个 ASP.NET 页面上覆盖相同的函数(渲染函数)

c++ - 在多重继承中避免菱形

python - 为什么在多重继承中执行 Base.__init__(self) 而不是 super().__init__() 时会跳过 __init__?

c++ - 我应该如何在菱形模式中调用父 move 构造函数?

c++ - 在 C++ 中搜索二进制文件定界符时得到不正确的偏移量

c++ - 在工作完成后立即删除 boost::thread 对象的最佳方法是什么?

java - 过滤器/组件模式而不是笨拙的继承?

c++ - 防止 C++ 中的多重继承

c++ - 使用条件运算符递归计算模板值或函数时出现错误 C1202(堆栈溢出)