我有一个给定main.cpp代码的家庭作业任务,不允许更改。根据那个主。
我的尝试是:我正在尝试创建4个班级,班级;班级工人;班级学生;班级服务;在我的主要功能中,通过实例化Inservice类的对象I传递4个参数(姓名,性别,sudenta no,workerno(;并在基类类型的指针的帮助下具有所需的输出。它显示的错误是:
[错误]'Virtual STD :: String Person :: getName(('在'Inservice'中没有唯一的最终超级效果[错误]没有唯一的"虚拟人员:: getSex(('in'inservice'
我试图为此使用虚拟继承,但是我真的不知道如何解决这个问题。我对虚拟继承进行了一些研究,并引用了其他专家的答案,但仍然与整个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;应该是个人::性= _sex;
您也可以删除名称和性虚拟功能,并亲自拥有标准功能,因为它的所有类别都完全相同。这将消除Inservice类虚拟表需要指向的getName和getSex函数的歧义。