#include<iostream>
using namespace std;
class person {
public:
person(string name, int num): name(name),num(num) {
cout << "person 输出" << endl;
}
private:
string name;
int num;
};
class teacher :virtual public person {
public:
teacher(string a, int b, int c) :person(a, b), age(c) {
cout << "teacher 输出" << endl;
}
private:
int age;
};
class student :virtual public person {
public:
student(string a, int b, int c) :person(a, b), sex(c) {
cout << "student 输出" << endl;
}
private:
int sex;
};
class me :public teacher, public student {
public:
me(string a, int b, int c, int d, int e) :person(a, b), student(a, b, c), teacher(a, b, d) {
dema = e;
cout << "me完事了" << endl;
}
private:
int dema;
};
int main() {
me("dema", 1, 2, 3, 4);
return 0;
}
结果:
person 输出
teacher 输出
student 输出
me完事了
虚基类解决了me继承的二义性,因为teacher和student都继承于person,me又继承于teacher和student 就会重复了person的成员数据。
注意:
1.person为虚基类 但virtual写在 teacher,student继承时
2.me的构造函数写法。
3.构造的顺序是按照
class me :public teacher, public student 来的 而不是构造函数初始化表的顺序 切记!
可以参考输出结果
4.在最后的派生类负责对直接基类初始化,还要对虚基类初始化。
c++编译系统只执行最后派生类对虚基类的构造函数调用,忽略虚基类的其他派生类,这就保证了虚基类的数据成员不会被多次初始化。