【发布时间】:2019-10-09 02:30:05
【问题描述】:
我有一个不允许更改的给定 main.cpp 代码的家庭作业。根据那个 main.cpp 和简单的 input 和 output(在下面)示例,我必须完成程序。我的尝试是:我正在尝试创建 4 个类,类 Person;班级工人;班级学生;服务类;在我的主要功能中,通过实例化 InService 类的一个对象,我传递了 4 个参数(姓名、性别、学生编号、工人编号);并借助基类类型的指针,获得所需的输出。它显示的错误是: [Error] no unique final overrider for 'virtual std::string Person::getName()' in 'InService' [错误] '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
【问题讨论】:
-
为什么 getname 和 getSex 用相同的代码实现了两次?你确定有必要吗?
-
InService应该如何知道它应该调用哪个函数?它有 2 种不同的实现可供选择。virtual继承有助于防止 base 类实现了方法。 -
为什么
sex和name是学生和工人的财产?人没有那些吗? -
@Federico 所以我正在关注本教程,据我所知,它是使用相同的函数名称来操作不同的对象。比如基类是shape,它有pur虚函数getArea;我们还有派生类,例如 Rectangle、Circle 和 Triangle。由于每个形状都有不同的计算,因此我们需要使用虚拟函数。 youtu.be/ng98qapa4Sw?t=1319
-
Worker和Student之间实际上有什么区别吗?我觉得你的设计需要修复,但我真的不明白你想要设计什么,看起来你可以忘记继承所有的东西来实现类似
标签: c++ multiple-inheritance virtual-inheritance