C++面向对象程序设计 - 多继承,以及基类与派生类转换

C++中多重继承、虚基类与继承与组合的理解与应用
本文详细介绍了C++中的多重继承,包括构造函数的使用,以及如何处理因继承导致的二义性问题。还讨论了虚基类的概念及其在解决继承冲突中的作用,以及基类与派生类之间的转换规则和组合的概念。

        单继承是一个类从另一个基类派生类而来的,多继承则是一个派生类是同两个或多个基类,派生类从两人或多个基类中继承所需的属性。

        声明多重继承的方法:

class D: public A, private B, protected C

{

        类D新增加的成员

}

一、多重继承派生类的构造函数

        多重继承派生类的构造函数形式与单继承时的构造函数形式基本相同,只是在初始表中包含多个基类构造函数。如:

派生类构造函数名 ( 总参数表列 ) : 基类1构造函数 ( 参数表列 ) ,基类2构造函数 (参数表列) ,基类3构造函数 (参数表列)

{

        派生类中新增数据成员初始化语句

}

        派生类构造函数的执行顺序:同样还是先调用基类的构造函数,再执行派生类构造函数的函数体。

示例代码:

#include <iostream>
#include <string>
using namespace std;
class Teacher{
	protected:
		string name;
		int age;
		string post;		//职称
	public:
		// 构造函数
		Teacher(string name, int age, string post): name(name), age(age), post(post){}
};
class Student{
	protected:
		string name;
		int age;
		int score;
	public:
		// 构造函数
		Student(string name, int age, int score): name(name), age(age), score(score){}
};
class Graduate: public Teacher, public Student{
	private:
		int wage;			//工资
	public:
		// 多继承构造函数
		Graduate(string name, int age, string post, int score, int wage):
			Teacher(name, age, post), Student(name, age, score), wage(wage){}
		// 显示信息
		void display(){
			cout <<"name:" <<Teacher::name <<endl;
			cout <<"age:" <<Teacher::age <<endl;
			cout <<"post:" <<post <<endl;
			cout <<"score:" <<score <<endl;
			cout <<"wage:" <<wage <<endl;
		}
};
int main(){
	// 实例对象
	Graduate graduate("Tom", 20, "history", 90.5, 5000);
	// 显示结果
	graduate.display();
	return 0;
}

        运行结果如下:

        注意的是,Teacher类和Student类中都有name和age数据成员,这样程序就不知道调用哪一个,没作指明则系统编译时会报错【[Error] reference to 'name' is ambiguous】- 对'name'的引入有歧义。但如何指明其作用域呢,上述代码中已经体现了,通过类名来指定作用域,如:

cout <<"name:" <<Teacher::name <<endl;

二、多重继承引起的二义性问题

        多重继承可以反映现实生活中的情况,能够用效地处理一些较复杂的问题,使编写程序具有灵活性,但是多重继承也引起了一些值得注意的问题,它增加了程序的复杂性,最常见的问题则是继承的成员同名而产生的二义性(ambiguous)问题。

(1)两个基类有同名成员。如下图:

        示例代码如下:

#include <iostream>
#include <string>
using namespace std;
class Teacher{
	protected:
		string name;
		int age;
		string post;		//职称
	public:
		// 构造函数
		Teacher(string name, int age, string post): name(name), age(age), po
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

觉醒法师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值