首页 > 解决方案 > 多重继承C++的钻石问题

问题描述

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

我试图为此使用虚拟继承,但我真的不知道如何解决这个问题。我对虚拟继承做了一些研究,并参考了其他专家的答案,但仍然对整个 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  

标签: c++multiple-inheritancevirtual-inheritance

解决方案


 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 中的标准函数,因为它对于从它派生的所有类都是完全相同的。这将消除 InService 类虚拟表需要指向哪个 getName 和 getSex 函数的歧义。


推荐阅读