C++ 类的继承(Inheritance)

一、继承(Inheritance)

  C++有一个很好的性质称为inheritance(继承),就是声明一个class(derived class),把另一个或多个class(base class)的所有内容(包括data members和member function)统统继承下来(有无存取权限是另一回事)。如果直接继承自一个base class ,称为单一继承;如果直接继承自一个以上的class,称为多重继承。语法如下(以下是三层单一继承):

 1 class CPoint
 2 {
 3 public:
 4     CPoint(float x=0.0):_x(x){}
 5     float x() {return _x;}
 6     void x(float xval){_x=xval;}
 7 protected:
 8     float _x;
 9 };
10 
11 class CPoint2d:public CPoint{
12 
13 public:
14     CPoint2d(float x=0.0,float y=0.0):CPoint(x),_y(y){}
15 
16    float y(){return _y;}
17    void y(float yval){_y=yval;}
18 protected:
19     float _y;
20 };
21 
22 class CPoint3d:public CPoint2d{
23 public:
24     CPoint3d(float x=0.0,float y=0.0,float z=0.0) :CPoint2d(x,y),_z(z){}
25     float z(){return _z;}
26     void z(float zval){_z=zval;}
27 
28 protected:
29     float _z;
30 
31 
32 };

  然后我们可以这样使用它们:

 1 CPoint3d aPoint3d(1.1, 2.2, 3.3);
 2 cout << "x = " << aPoint3d.x() << endl; // 1.1
 3 cout << "y = " << aPoint3d.y() << endl; // 2.2
 4 cout << "z = " << aPoint3d.z() << endl; // 3.3
 5 CPoint3d* pPoint3d = new CPoint3d(4.4, 5.5, 6.6);
 6 pPoint3d->x(4.1); // x() 是 CPoint's member function
 7 pPoint3d->y(5.2); // y() 是 CPoint2d's member function
 8 pPoint3d->z(6.3); // z() 是 CPoint3d's member function
 9 cout << sizeof(CPoint) << endl; // 4
10 cout << sizeof(CPoint2d) << endl; // 8
11 cout << sizeof(CPoint3d) << endl; // 12

  我们在CPint3d object中使用继承而来的x() 和y()函数,这两个函数将存取继承而来的_x和 _y数据。继承的最大用意,在于表现对象世界中is a kind of(或说is a)的关系。以本例CPoint3d object为例,其结构示意图如下:  

  C++语言支持三种继承:

  1.单一继承(single Inheritance):direct base class只有一个。

  2.多重继承(Multiple Inheritance):direct base class不只一个。 

  3.虚拟继承(Virtual Inheritance):多重继承之下,让共同的“祖父级”base class object能够被共享,不至于浪费内存空间。

二、单一继承(single Inheritance)

  所谓单一继承,就是每一个class的driectly base class 只能有一个,继承的层级数目并没有限制。上例的CPoint、CPoint2d、CPoint3d一脉相传就是一种单一继承:

 

三、多重继承(Multiple Inheritance)

  所谓多重继承,就是每一个class的driectly base class 不只一个,多重继承的语法如下:

 

 四、虚拟继承(Virtual Inheritance)

  所谓虚拟继承,就是在class head中,于base class的前方加上virtual关键字,如下所示:

 

 五、继承体系下的对象构造和析构

  1.继承体系下的对象构造顺序是:先内后外,先上后下;

CPoint's constructor. // 先建构 CPoint subobject
CPoint2d's constructor. // 再建构 CPoint2d subobject
CPoint3d's constructor. // 最后建构 CPoint3d object

 

        2.继承体系下的对象析构顺序是:先外后内,先下后上;

CPoint3d's destructor. // 先析构 CPoint3d 外围部份
CPoint2d's destructor. // 再析构 CPoint2d 部份
CPoint's destructor. // 最后析构 CPoint 部份

 

posted on 2024-05-10 12:40  阮春义  阅读(256)  评论(0编辑  收藏  举报

导航