//练习一下虚继承和虚函数
题目描述
1、建立如下的类继承结构:
1) 定义一个人员类CPeople,其属性(保护类型)有:姓名、性别、年龄;
2) 从CPeople类派生出学生类CStudent,添加属性:学号和入学成绩;
3) 从CPeople类再派生出教师类CTeacher,添加属性:职务、部门;
4) 从CStudent和CTeacher类共同派生出在职研究生类CGradOnWork,添加属性:研究方向、导师;
2、分别定义以上类的构造函数、输出函数print及其他函数(如需要)。
3、在主函数中定义各种类的对象,并测试之。
样例输入
wang-li m 23
2012100365 92.5
assistant computer
robot zhao-jun
样例输出
People:
Name: wang-li
Sex: m
Age: 23
Student:
Name: wang-li
Sex: m
Age: 23
No.: 2012100365
Score: 92.5
Teacher:
Name: wang-li
Sex: m
Age: 23
Position: assistant
Department: computer
GradOnWork:
Name: wang-li
Sex: m
Age: 23
No.: 2012100365
Score: 92.5
Position: assistant
Department: computer
Direction: robot
Tutor: zhao-jun
#include <iostream>
#include <string>
using namespace std;
class CPeople{
protected:
string name,sex;
int age;
public:
CPeople(string na,string se,int ag):name(na),sex(se),age(ag) { }
virtual void print(){
cout<<"People:"<<endl;
CPeople::printLocal();
cout<<endl;
}
virtual void printLocal(){
cout<<"Name: "<<name<<endl;
cout<<"Sex: "<<sex<<endl;
cout<<"Age: "<<age<<endl;
}
};
class CStudent:virtual public CPeople{
protected:
string no;
float score;
public:
CStudent(string na,string se,int ag,string n,float s):CPeople(na,se,ag),no(n),score(s) { }
virtual void print(){
cout<<"Student:"<<endl;
CPeople::printLocal();
CStudent::printLocal();
cout<<endl;
}
virtual void printLocal(){
cout<<"No.: "<<no<<endl;
cout<<"Score: "<<score<<endl;
}
};
class CTeacher:virtual public CPeople{
protected:
string position,department;
public:
CTeacher(string na,string se,int ag,string p,string d):CPeople(na,se,ag),position(p),department(d) { }
virtual void print(){
cout<<"Teacher:"<<endl;
CPeople::printLocal();
CTeacher::printLocal();
cout<<endl;
}
virtual void printLocal(){
cout<<"Position: "<<position<<endl;
cout<<"Department: "<<department<<endl;
}
};
class CGradOnWork:public CStudent,public CTeacher{
protected:
string direction,tutor;
public:
CGradOnWork(string na,string se,int ag,string no,float sc,string po,string de,string di,string tu):CPeople(na,se,ag),CStudent(na,se,ag,no,sc),CTeacher(na,se,ag,po,de),direction(di),tutor(tu) { }
virtual void print(){
cout<<"GradOnWork:"<<endl;
CPeople::printLocal();
CStudent::printLocal();
CTeacher::printLocal();
CGradOnWork::printLocal();
}
virtual void printLocal(){
cout<<"Direction: "<<direction<<endl;
cout<<"Tutor: "<<tutor<<endl;
}
};
int main(){
string name,sex,no,position,department,direction,tutor;
int age;
float score;
cin>>name>>sex>>age>>no>>score>>position>>department>>direction>>tutor;
CGradOnWork cgow(name,sex,age,no,score,position,department,direction,tutor);
cgow.CPeople::print();
cgow.CStudent::print();
cgow.CTeacher::print();
cgow.print();
return 0;
}