简体   繁体   English

具有3个派生类的C ++中的多重继承

[英]Multiple Inheritance in C++ with 3 derived classes

I'm trying to use multiple inheritance. 我正在尝试使用多重继承。 Person is my base class. 是我的基层。 Student and Angestellter inherit the protected attributes. StudentAngestellter继承受保护的属性。 WissenschaftlicheHilfskraft should also inherit these attributes (from Person, Student, Angestellter), but I can't call the method get_name() in my last derived class. WissenschaftlicheHilfskraft也应该继承这些属性(来自Person,Student和Angestellter),但是我不能在上一个派生类中调用get_name()方法。 Why? 为什么?

#include <iostream>

using namespace std;

class Person {
      protected:
              string name;
      public:              //.......
          string get_name() { name = "bob"; return name; }
};

class Student: public Person {
private:    //......
public:     //......
};

class Angestellte: public Person {
private:    //......
public:    //......
};

class WissenschaftlicheHilfskraft : public Student, public Angestellte
{
private: //......
public: //......
};


int main()
{
    Person p;
    cout << p.get_name() << endl;   //WORKS
    Student s;
    cout << s.get_name() << endl;   //WORKS
    Angestellte a;
    cout << a.get_name() << endl;   //WORKS
    WissenschaftlicheHilfskraft wh;
    cout << wh.get_name() << endl;  //DOESN'T WORK
    return 0;
}

I want it to look like this: 我希望它看起来像这样: 在此处输入图片说明

This is the classic "diamond" problem with multiple inheritance. 这是具有多重继承的经典“钻石”问题。 You can work around this by removing the ambiguity, eg change: 您可以通过消除歧义来解决此问题,例如,更改:

cout << wh.get_name() << endl;  //DOESN'T WORK

to: 至:

cout << wh.Student::get_name() << endl;  //WORKS

However, see @Shiv's answer for a better solution which properly resolves the underlying problem. 但是,请参阅@Shiv的答案以获得更好的解决方案,该解决方案可以正确解决潜在的问题。

Also, other than Paul R's answer your inheritance is wrong. 另外,除了Paul R的回答,您的继承是错误的。 You need to use virtual inheritance like as shown here . 您需要使用虚拟继承等作为显示在这里

class Student: public Person { becomes class Student: public virtual Person { and so on. class Student: public Person {成为class Student: public virtual Person {依此类推。 This ensures that only one object of base is created for the final object. 这样可以确保只为最终对象创建一个base对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM