【问题标题】:How does C++ deal with Multiple inheritance( NOT the diamond one) [duplicate]C ++如何处理多重继承(不是钻石继承)[重复]
【发布时间】:2017-09-03 07:12:16
【问题描述】:

C++可以利用虚拟基类的概念来解决多重继承问题。但是我到处都看到用菱形问题来说明虚拟基类的使用。以下面给出的这个例子为例。这也是多重继承。但是如何使用虚拟基类来解决这个问题呢?这给出了编译错误。请有人指出我正在做的错误。 谢谢

#include<iostream>
using namespace std;

class Parent1 {
    public:
         void fun();
};

void Parent1::fun(){
    cout<<"Parent1"<<endl;
}
class Parent2{
    public: void fun()
    {
        cout<<"Parent2"<<endl;
    }
};

class Child:public virtual Parent1,public virtual Parent2
{

};
int main()
{
    Child c;
    c.fun();
}

【问题讨论】:

  • 多重继承是关于你从多个类派生的事实,而不是关于存在同名函数的事实。 多重继承问题不存在。
  • 是的,你是对的。但我们最终可能会因此而面临这样的问题。这就是我想问的原因。

标签: c++


【解决方案1】:

继承没有问题,只是名称冲突,很容易解决。

#include<iostream>

using namespace std;

class Parent1 {
public:
    void fun() {
        cout << "Parent1" << endl;
    }
};

class Parent2 {
public:
    void fun() {
        cout<<"Parent2"<<endl;
    }
};

class Child:public virtual Parent1,public virtual Parent2
{
public:
    using Parent1::fun;
};

int main()
{
    Child c;
    c.fun();
}

【讨论】:

  • 无论哪种方式,您仍然可以完全符合会员c.Parent2::fun();
猜你喜欢
  • 2016-09-21
  • 1970-01-01
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 2011-02-09
相关资源
最近更新 更多