虚基类的应用——c++对c的扩充(12)

实现,两个类有相同的基类,并且同时作为另一个类的基类。

利用虚基类,在定义这两个类时,在继承关系前写上关键词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)删掉
在这里插入图片描述
结果就如下图所示,很明显,第二次输入是,数据是没有传进去的。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值