其中,Data_rec 是虚基类,它包含了所有派生类共有的数据成员,职工类 Employee 和学生类 Student 为虚基类 Data_rec 的派生类,教师类 Teacher 为职工类 Employee 的派生类,在职大学生类 E_Student 是职工类 Employee 和学生类 Student 的共同派生类。每个类定义了一个相对于特定类的不同的 print 函数,输出各类的数据成员。
#include
#include
using namespace std;
class Data_rec{ //声明基类 Data_rec
protected:
string name; //姓名
char sex; //性别
int age; //年龄
public:
Data_rec(string name1,char sex1,int age1){ //声明基类 Data_rec
name=name1;
sex=sex1;
age=age1;
}
void print(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"sex:"<<sex<<endl;
}
};
class Student:virtual public Data_rec{ //声明类 Data_rec 是 Student 的虚基类
protected:
string major; //专业
double score; //成绩
public:
Student(string name1,int age1,char sex1,string major1,double score1):Data_rec(name,sex,age){
major=major1;
score=score1;
}
void print(){
Data_rec::print();
cout<<"score:"<<score<<endl;
cout<<"major:"<<major<<endl;
}
};
class Employee:virtual public Data_rec{ //声明类 Data_rec 是 Employee 的虚基类
protected:
string dept; //部门
double salary; //酬金
public:
Employee(string name1,char sex1,int age1,string dept1,double salary1):Data_rec(name1,sex1,age1){
dept=dept1;
salary=salary1;
}
void print(){
Data_rec:print();
cout<<"department:"<<dept<<endl;
cout<<"salary:"<<salary<<endl;
}
};
class Teacher:public Employee{ //声明类 Teacher 为类 Employee 的派生类
protected:
string title; //职称
public:
Teacher(string name1,char sex1,int age1,string dept1,double salary1,string title1)
:Data_rec(name1,sex1,age1),Employee(name1,sex1,age1,dept1,salary1){
title=title1;
}
void print(){
Employee::print();
cout<<"title:"<<title<<endl;
}
};
class E_Student:public Employee,public Student{ //声明类 E_Student 为类 Employee 和类 Student 的派生类
public:
E_Student(string name1,char sex1,int age1,string major1,double score1,string dept1,double salary1):Data_rec(name1,sex1,age1),
Student(name1,sex1,age1,major1,score1),Employee(name1,sex1,age1,dept1,salary1){
}
void print(){
Student::print();
cout<<"department:"<<dept<<endl;
cout<<"salary:"<<salary<<endl;
}
};
int main(){
Student my_Student("小红",'f',22,"应用数学",90);
cout<<"Student:"<<endl;
my_Student.print();
Employee my_Employee("小成",'m',23,"科研处",5000);
cout<<"Employee:"<<endl;
my_Employee.print();
Teacher my_Teacher("小黄",'f',50,"管理学院",8000,"教授");
cout<<"Teacher"<<endl;
my_Teacher.print();
E_Student my_E_Student("小吕",'m',34,"计算机",95,"教务处",3500);
cout<<"E_Student:"<<endl;
my_E_Student.print();
return 0;
}