一、多继承
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、将派生类对象赋值给基类对象
基类不包含派生类的成员变量,无法对派生类的成员变量赋值。同理,同一基类的不同派生类对象之间也不能赋值。