文档介绍:§ 基类和派生类
第十四章目录
§ 派生类的三种继承方式
§ 派生类的定义格式
§ 派生类的构造函数和析构函数
§ 多继承
§ 多继承中的二义性问题
第十四章小结
§ 虚基类
继承(Hierarchy)是C++ 语言的一种重要机制。继承是指把已有的类作为基类来定义新的类。新类继承了其基类的属性和操作,还可以具有其基类不具备的自己特有的属性和操作。
继承性为软件的编写提供了强有力的机制,提高了软件的可靠性、易读性、有效性、可移植性和可重用性。
本章主要内容有:基类和派生类,单继承和多继承,虚基类。
第十四章继承性和派生类
生物学中的遗传(或称继承)的概念是指所有生物都从其祖先那里继承了一些特征。
继承的概念可以用于设计复杂的系统,它提供了将系统的组成部分组织成一个继承结构的方法,以利于对系统的描述。
同时它还提供了一个代码重用的结构。
在C++ 中,如果有一个类B 继承了类A,或从类A 派生出类B,通常称类A 为基类(父类),称类B 为派生类(子类)。
类B 不但拥有类A 的属性,而且还可以拥有自己新的属性。
§ 基类和派生类(Base classes and derived classes)
在C++ 中,继承分为单继承和多继承:
单继承——派生类只有一个直接基类的继承方式;
多继承——派生类有多个直接基类的继承方式。
如下图所示:
外部存储器
软盘
光盘
硬盘
单继承
A
B
C
单继承
X
Y
Z
多继承
§ 派生类的定义格式
1、单继承派生类的定义格式
class <派生类名>:<继承方式><基类名>
{
//<派生类新成员的定义>
}
其中,派生类名是自定义的派生类名字,并且派生类是按指定的继承方式派生的。继承方式有:
public 公有继承
private 私有继承
protected 保护继承
2、多继承派生类的定义格式
class <派生类名>:<继承方式1> <基类名1>,
<继承方式2> <基类名2>,…
{
//<派生类新成员定义>
};
多继承派生类有多个基类,基类名之间用逗号分隔,每个基类名前都应有一个该基类的继承方式说明。
缺省的继承方式为私有继承。
例如:类A 是基类,类B 是类A 的派生类,定义格式如下:
class A
{
public:
A(int i)
{ a=i; }
void print()
{ cout<<a<<endl; }
private:
int a;
};
class B: public A
{
public:
//…
private:
int b;
};
1、公有继承方式(public)
基类中的每个成员在派生类中保持同样的访问权限;
2、私有继承方式(private)
基类中的每个成员在派生类中都是private成员,而且它们不能再被派生的子类所访问;
3、保护继承方式(protected)
基类中的public成员和protected成员在派生类中都是protected成员,private成员在派生类中仍为private成员。
§ 派生类的三种继承方式
Access Control(Including derived classes)
A member of a class can be private, protected, or public:
If it is private, its name be used only by member function and friends of the class in which it is declared.
If it is protected, its name can be used only by member functions and friends of the class in which it is declared and by member functions and friends of classes derived from this class.
If it is public, its name can be used by any function.
public:
protected:
private:
general users
derived class member functions and friends
member functions and friends