虚基类简介

#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++编译系统只执行最后派生类对虚基类的构造函数调用,忽略虚基类的其他派生类,这就保证了虚基类的数据成员不会被多次初始化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值