继承与派生
一. 继承与派生
通过继承机制,可以利用已有的数据类型来定义新的数据类型。所定义的新的数据类型不仅拥有新定义的成员,而且还同时拥有旧的成员。我们称已存在的用来派生新类的类为基类,又称为父类。由已存在的类派生出的新类称为派生类,又称为子类。当创建一个类时,不需要重新编写新的数据成员和成员函数,只需指定新建的类继承了一个已有的类的成员即可。
单继承的定义格式如下:
1 class<派生类名>:<继承方式><基类名> 2 { 3 <派生类新定义成员> 4 };
其中,class是关键词,<派生类名>是新定义的一个类的名字,它是从<基类名>中派生的,并且按指定的<继承方式>派生的。<继承方式>常使用如下三种关键字给予表示:
public 表示公有继承;
private 表示私有继承;
protected 表示保护继承;
实列如下:
1 include <iostream> 2 3 using namespace std; 4 5 // 基类 6 class Shape //定义基类Shape 7 { 8 public: 9 void setWidth(int w) 10 { 11 width = w; 12 } 13 void setHeight(int h) 14 { 15 height = h; 16 } 17 protected: 18 int width; 19 int height; 20 }; 21 22 // 派生类 23 class Rectangle: public Shape //定义派生类Rectangle 24 { 25 public: 26 int getArea() 27 { 28 return (width * height); 29 } 30 }; 31 32 int main(void) 33 { 34 Rectangle Rect; 35 36 Rect.setWidth(5); 37 Rect.setHeight(7); 38 39 // 输出对象的面积 40 cout << "Total area: " << Rect.getArea() << endl; 41 42 return 0; 43 }
运行该代码结果如下:
二. 多继承
多继承即一个子类可以有多个父类,它继承了多个父类的特性。
C++ 类可以从多个类继承成员,语法如下:
1 class <派生类名>:<继承方式1><基类名1>,<继承方式2><基类名2>,… 2 { 3 <派生类类体> 4 };
其中,访问修饰符继承方式是 public、protected 或 private 其中的一个,用来修饰每个基类,各个基类之间用逗号分隔,如上所示。现在让我们一起看看下面的实例:
1 #include <iostream> 2 3 using namespace std; 4 5 // 基类 Shape 6 class Shape 7 { 8 public: 9 void setWidth(int w) 10 { 11 width = w; 12 } 13 void setHeight(int h) 14 { 15 height = h; 16 } 17 protected: 18 int width; 19 int height; 20 }; 21 22 // 基类 PaintCost 23 class PaintCost 24 { 25 public: 26 int getCost(int area) 27 { 28 return area * 70; 29 } 30 }; 31 32 // 派生类 33 class Rectangle: public Shape, public PaintCost 34 { 35 public: 36 int getArea() 37 { 38 return (width * height); 39 } 40 }; 41 42 int main(void) 43 { 44 Rectangle Rect; 45 int area; 46 47 Rect.setWidth(5); 48 Rect.setHeight(7); 49 50 area = Rect.getArea(); 51 52 // 输出对象的面积 53 cout << "Total area: " << Rect.getArea() << endl; 54 55 // 输出总花费 56 cout << "Total paint cost: $" << Rect.getCost(area) << endl; 57 58 return 0;
代码运行结果为:
三. 多种继承方式
公有继承(public)、私有继承(private)、保护继承(protected)是常用的三种继承方式。
1. 公有继承(public)
公有继承的特点是基类的公有成员和保护成员作为派生类的成员时,它们都保持原有的状态,而基类的私有成员仍然是私有的,不能被这个派生类的子类所访问。
2. 私有继承(private)
私有继承的特点是基类的公有成员和保护成员都作为派生类的私有成员,并且不能被这个派生类的子类所访问。
3. 保护继承(protected)
保护继承的特点是派生类的所有公有成员和保护成员都成为派生类的保护成员,并且只能被它的派生类成员函数或友元访问,基类的私有成员仍然是私有的。
下面列出三种不同的继承方式的基类特性和派生类特性。
public
|
protected
|
private
|
|
公有继承
|
public
|
protected
|
不可见
|
私有继承
|
private
|
private
|
不可见
|
保护继承
|
protected
|
protected
|
不可见
|