多继承C ++的钻石问题

时间:2019-05-22 14:50:13

标签: c++ multiple-inheritance virtual-inheritance

我有一个具有给定main.cpp代码的家庭作业,不允许更改。根据该main.cpp和简单的 input output (下面是示例)的示例,我必须完成该程序。我的尝试是:我正在尝试创建4个类,即Person类;工人阶级班级学生; InService类;在我的主要功能中,通过实例化InService类的对象,我传递了4个参数(名称,性别,studentNo,workerNo);并借助基类类型的指针,获得所需的输出。它显示的错误是: [错误]'InService'中的'虚拟std :: string Person :: getName()'没有唯一的最终替代。           [错误]对于“ InService”中的“虚拟int Person :: getSex()”,没有唯一的最终替代项。

我已经尝试使用虚拟继承,但是我真的无法弄清楚如何解决这个问题。我对虚拟继承进行了一些研究,并参考了其他专家answers,但仍然对整个OOP感到困惑。

//Inservice.h
#include<string>
using namespace std;
class Person{
    public:
        Person();
        ~Person();      
        string name;
        int sex;
        virtual string getName() = 0;
        virtual int getSex()  = 0;
};
///////////////////////////////////////////////////
class Student:virtual public Person{
    public:
        Student();
        ~Student();
        string sno;

        virtual string getName() {
        return name;
        }

        virtual int getSex(){
            return sex;
        }

        string getSno(){
            return sno;
        }
};
//////////////////////////////////////////////////
class Worker:virtual public Person{
    public:
        Worker();
        ~Worker();
        string wno;

        virtual std::string getName(){
        return name;
        }

        virtual int getSex(){
            return sex;
        }

        string getWno(){
            return wno;
        }
};
///////////////////////////////////////////////////////
class InService: public Student, public Worker{
    public:
    InService(string _name, int _sex, string _sno, string _wno){
        Person::name = _name;
        Person::sex - _sex;
        Worker::wno = _wno;
        Student::sno = _sno;
    }
};
///////////////////////////////////////////////////////

//main.cpp
#include <iostream>
#include "inservice.h"
using namespace std;

int main() {
    string name, sno, wno;
    int sex;

    cin >> name;
    cin >> sex;
    cin >> sno;
    cin >> wno;

    InService is(name, sex, sno, wno);

    Person* p = &is;
    Student* s = &is;
    Worker* w = &is; 

    cout << p->getName() << endl;
    cout << p->getSex() << endl;

    cout << s->getName() << endl;
    cout << s->getSex() << endl;
    cout << s->getSno() << endl;

    cout << w->getName() << endl;
    cout << w->getSex() << endl;
    cout << w->getWno() << endl;
    return 0;
}

假设我的输入是:

Jack  
1 //1-for male; 0 -for female  
12345678 //studentNo
87654321  //workerNo  

我希望输出为:

Jack  
1  
12345678   
Jack  
1  
87654321  

1 个答案:

答案 0 :(得分:0)

 InService(string _name, int _sex, string _sno, string _wno){
        Person::name = _name;
        Person::sex - _sex;
        Worker::wno = _wno;
        Student::sno = _sno;
    }

那里有一个错字,Person :: sex-_sex;应该是Person :: sex = _sex;

您还可以删除名称和性别虚拟函数,并使其成为Person中的标准函数,因为对于所有派生自其的类来说,该函数都完全相同。这将消除InService类虚拟表需要指向哪个getName和getSex函数的歧义。

相关问题