3. 继承

继承是允许一个类(子类或派生类)基于另外一个类(父类或基类)创建,并继承基类的成员变量和成员函数。

继承的作用:

  1. 将公有部分放入基类,实现代码共享。
  2. 子类可以在原有的基础上添加新的功能。

继承的语法:

class 子类名继承方式 基类名 {
   ...
};

继承方式

继承后的访问权限表

基类访问权限
继承方式
本类访问权限
public
public
public
protected
public
protected
private
public
不可访问
public
protected
protected
protected
protected
protected
private
protected
不可访问
public
private
private
protected
private
private
private
private
不可访问

显式调用父类的构造函数的语法

class 子类名继承方式 基类名 {
     public:
          子类名(形参列表): 基类名(实参),成员变量1(实参),成员变量2(实参){...}
};

示例

/ filename: inherit.cpp
#include <iostream>

using namespace std;

// 点类(描述一个点的位置,面积等信息)
class Point {
    public:
        Point(float ax=0, float ay=0):x(ax), y(ay) {
            cout << "Point(" << x << "," << y << ")\n";
        }
        void info(void) {
            cout << "点(" << x << "," << y << ")\n";
        }
        void moveTo(float new_x, float new_y) {
            x = new_x; y = new_y;
        }
        float getArea(void) { // 获取图形面积
            return 0;
        }
    public:
        float x;
        float y;
};
// 圆类(描述圆的位置、半径、面积等信息)
class Circle : public Point {
    public:
        Circle(float ax, float ay, float radius)
            : Point(ax, ay), r(radius) {
            //  x = ax; y = ay; r = radius;
            cout << "Circle(" << x << "," << y << "," << r << ")\n";
        }
        void info(void) {
            cout << "圆(" << x << "," << y << "," << r << ")\n";
        }
    public:
        float r; // 半径
};

int main(int argc, char * argv[]) {
    Point p1(3, 5);
    Circle c1(4, 6, 10);

    cout << "sizeof(p1)" << sizeof(p1) << endl;
    cout << "sizeof(c1)" << sizeof(c1) << endl;
    c1.info();
    p1.info();
    p1.moveTo(100, 105);
    // 子类对象不存在moveTo,则调用父类的方法
    c1.moveTo(200, 210);
    p1.info();
    c1.info();
    cout << "程序结束!" << endl;
    return 0;
}

编译和运行结果如下:

weimz@mzstudio:~$ g++ -o inherit inherit.cpp
weimz@mzstudio:~$ ./inherit 
Point(3,5)
Point(4,6)
Circle(4,6,10)
sizeof(p1)8
sizeof(c1)12(4,6,10)(3,5)(100,105)(200,210,10)
程序结束!