9、面向对象-多继承

一、多继承

1、概念

一个类继承了多个类

语法:

class  派生类名 : 访问控制  基类名1 ,  访问控制  基类名2 ,  … , 访问控制  基类名n
{
         数据成员和成员函数声明
};

2、多继承的派生类的构造和访问

构造的顺序:先构造基类,再构造派生类。基类的构造顺序和继承顺序有关

#include <iostream>

using namespace std;

class Airplane
{
protected:
	int high;
public:
	Airplane()
	{
		cout << "飞机的构造函数" << endl;
		high = 100;
	}
	void show()
	{
		cout << "飞行高度" << high << endl;
	}
};

class Ship
{
protected:
	int speed;
public:
	Ship()
	{
		cout << "轮船的构造函数" << endl;
		speed = 50;
	}
	void show()
	{
		cout << "航行的速度" << speed << endl;
	}
};

class WaterPlane : public Airplane,public Ship   //多继承
{
public:
	WaterPlane()
	{
		cout << "水上飞机构造函数" << endl; 
	}
};

int main()
{
	WaterPlane w;

	cout << sizeof(w) << endl;
	w.Airplane::show();
	w.Ship::show();

	return 0;
}

3、多继承的二义性

1、概念:多个基类包涵命名一样的变量

#include <iostream>

using namespace std;

class TestA
{
public:
	int a;
};

class TestB : public TestA
{
public :
	int b;
};

class TestC : public TestA
{
public:
	int c;
};

class TestD : public TestB, public TestC
{
public:
	int d;
};

int main()
{
	TestD td;
	
	//td.TestB::a;      //会发生歧义,浪费空间

	cout << sizeof(td) << endl;

	return 0;
}

2、解决方法

虚继承:是类生成一个虚基类指针,指向基类成员    

关键字 virtual

双重虚继承:有两个虚继承指针。

偏移量对齐

#include <iostream>

using namespace std;

class TestA
{
public:
	int a;
};

class TestB :virtual public TestA     //虚继承testA  变成虚基类指针 指向 基类在哪
{
public :
	int b;
};

class TestC :virtual public TestA
{
public:
	int c;
};

class TestD : public TestB, public TestC
{
public:
	int d;
};

int main()
{
	TestD td;
	
	//td.TestB::a;      //会发生歧义,浪费空间

	cout << sizeof(td) << endl;

	cout << "********" << endl;

	TestB tb;
	cout << sizeof(tb) << endl;
	cout << &tb << endl;
	cout << &tb.a << endl;
	cout << &tb.b << endl;

	/*cout << &td << endl;
	cout << &td.a << endl;
	cout << &td.b << endl;
	cout << &td.c << endl;
	cout << &td.d << endl;*/

	return 0;
}

二、C++向上转型(赋值时可以舍去多的部分)

1、将派生类对象赋值给基类对象

基类不包含派生类的成员变量,无法对派生类的成员变量赋值。同理,同一基类的不同派生类对象之间也不能赋值。

2、将派生类指针赋值给基类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值