分别声明Teacher(教师)类和Cadre(干部)类,采用多重继承方式由这两个类派生出新类Teacher_Cadre(教师兼干部)。
要求:
①在两个基类中都包含一部分相同名字的数据成员name(姓名),age(年龄)和成员函数display()。
②在Teacher类中还包含数据成员title(职称),在Cadre类中还包含数据成员post(职务),在Teacher_Cadre(教师兼干部)中还包含数据成员wages(工资)。
③在派生类Teacher_Cadre的成员函数show输出姓名、年龄、职称,职务与工资。
④主函数定义Teacher_Cadre对象tc,输出其信息。
#include<iostream>
#include<string>
using namespace std;
class teacher{ //第一个基类teacher
public:
teacher() {
cout << "Please enter the name,age and title:" << endl;
cin >> name >> age>> title;
cout<<endl;
}
void display() {
cout << "This person's information: " <<endl<< "name: "<<name<<"age: "<<age<<"title: "<<title;
}
protected: //protected成员可被派生类的成员函数访问
string name;
string title;
int age;
};
class cadre { //第二个基类cadre
public:
cadre() {
cout << "Please enter the name,age and post:" << endl;
cin >> name>>age>>post;
cout << endl;
}
void display() {
cout << "This person's information: " <<endl<< "name: " << name << "age: " << age << "post: " << post;
}
protected:
string name;
string post;
int age;
};
class teacher_cadre:public teacher,public cadre{ //对第一,二两个基类的双重继承的派生类teacher_cadre
public:
teacher_cadre() { //派生类的构造函数只需对派生类新增成员进行构造
cout << "Please enter the wages: " << endl;
cin >>wages;
cout << endl;
}
void display() { //派生类调用两个基类共有成员时,加作用域符进行指定
cout << "This person's information: " << endl;
cout << "name: " << teacher::name << endl;
cout << "age: " << teacher::age << endl;
cout << "title: " << title << endl;
cout << "post: " << post << endl;
cout << "wages: " << wages<<endl;
}
protected:
double wages;
};
int main() {
teacher_cadre tc;
tc.teacher_cadre::display(); //基类与派生类含有同名函数时,可加作用域符::进行指定
return 0;
}
派生类中继承基类的部分由基类的初始化构造函数完成构造 ⬇