多继承C++的钻石问题

Diamond problem with Multiple inheritance C++

我有一个家庭作业,给定的 main.cpp 代码不允许更改。根据 main.cpp 和简单的 inputoutput(在下面)示例,我必须完成程序。我的尝试是:我正在尝试创建 4 classes,class 人; class 工人; class学生; class 在职;在我的主要功能中,通过实例化 InService class 的对象,我传递了 4 个参数(姓名、性别、学生编号、工人编号);并借助 Base class 类型的指针,获得所需的输出。它显示的错误是:[错误] 'InService' 中的 'virtual std::string Person::getName()' 没有唯一的最终覆盖 [错误] 'InService'

中 'virtual 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  
 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;

您还可以删除 name 和 sex 虚拟函数,并使其成为 Person 中的标准函数,因为它对于从它派生的所有 classes 完全相同。这将消除 InService class virtual table 需要指向哪个 getName 和 getSex 函数的歧义。