实现,两个类有相同的基类,并且同时作为另一个类的基类。
利用虚基类,在定义这两个类时,在继承关系前写上关键词virtual,则 将两者公有的两份基类数据,在传给另一个类时只有一份。
# include <iostream>
using namespace std;
class human {
string name;
int age;
char sex;
string add;
string num;
public:
human();
human(string a, int b, char c, string d, string e) {
name = a;
age = b;
sex = c;
add = d;
num = e;
}
void display();
};
void human::display() {
cout << "name = " << name << endl;
cout << "age = " << age << endl;
cout << "sex = " << sex << endl;
cout << "add = " << add << endl;
cout << "num = " << num << endl;
}
human::human() {
name = "**";
age = 0;
sex = '*';
add = "**";
num = "***";
}
class Teacher :virtual public human{
public:
Teacher();
Teacher(string a, int b, char c, string d, string e,string x): human(a,b,c,d,e) {
title = x;
}
void display1();
private:
string title;
};
Teacher::Teacher() {
title = "****";
}
void Teacher:: display1() {
display();
cout << "title = " << title << endl;
}
class Cadre :virtual public human{
public:
Cadre();
Cadre(string a, int b, char c, string d, string e,string y) : human(a, b, c, d, e) {
post = y;
}
void display2();
private:
string post;
};
Cadre::Cadre() {
post = "*****";
}
void Cadre::display2() {
display();
cout << "title = " << post << endl;
}
class Teacher_Cadre :public Teacher, public Cadre {
private:
int wages;
public:
Teacher_Cadre();
Teacher_Cadre(string a, int b, char c, string d, string e, string y,string z,int w):human(a,b,c,d,e),Teacher(a,b,c,d,e,y),Cadre(a,b,c,d,e,z),wages(w){
}
void show();
};
Teacher_Cadre::Teacher_Cadre(){
wages = 0;
}
void Teacher_Cadre::show() {
Teacher::display1();
cout << wages << endl;
}
int main() {
Teacher_Cadre st;
st.show();
string a;
int b;
char c;
string d;
string e;
string y;
string z;
int w;
cin >> a >> b >> c >> d >> e >> y >> z >> w;
Teacher_Cadre st1(a, b, c, d, e, y, z, w);
st1.show();
return 0;
}
正常运行结果:
需要特别注意:在写构造函数的时候,子类必须把父类的数据也同时赋值初始化
例子:
当我把代码如下图的部分,把human(a, b, c, d, e)删掉
结果就如下图所示,很明显,第二次输入是,数据是没有传进去的。