C++ 继承
面向对象编程中最重要的概念之一是继承。继承允许我们根据另一个类来定义一个类,这使得应用程序的创建和维护更加容易。这也提供了重用代码功能和加快实现速度的机会。
创建类时,程序员可以指定新类继承现有类的成员,而无需编写全新的数据成员和成员函数。这个现有类称为基类,而新类称为派生类。
继承的思想实现了是关系。例如,哺乳动物是动物,狗是哺乳动物,因此狗也是动物,等等。
基类和派生类
一个类可以从多个类派生,这意味着它可以从多个基类继承数据和函数。要定义派生类,我们使用类派生列表来指定基类。类派生列表命名一个或多个基类,其形式为:-
class derived-class: access-specifier base-class
其中 access-specifier 是 public、protected 或 private 之一,base-class 是先前定义的类的名称。如果未使用访问说明符,则默认为私有。
考虑一个基类 Shape 及其派生类 Rectangle,如下所示 -
#include <iostream> using namespace std; // 基类 class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // 派生类 class Rectangle: public Shape { public: int getArea() { return (width * height); } }; int main(void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); // 打印对象的面积。 cout << "Total area: " << Rect.getArea() << endl; return 0; }
当编译并执行上述代码时,它会产生以下结果 -
Total area: 35
访问控制与继承
派生类可以访问其基类的所有非私有成员。因此,派生类成员函数无法访问的基类成员应在基类中声明为私有成员。
我们可以根据访问对象来总结不同的访问类型,如下所示:
访问 | public | protected | private |
---|---|---|---|
Same class | yes | yes | yes |
Derived classes | yes | yes | no |
Outside classes | yes | no | no |
派生类继承所有基类方法,但以下方法除外:
- 基类的构造函数、析构函数和复制构造函数。
- 基类的重载运算符。
- 基类的友元函数。
继承类型
从基类派生类时,基类可以通过public、protected或private继承进行继承。继承类型由访问说明符指定,如上所述。
我们很少使用protected或private继承,但通常使用public继承。使用不同类型的继承时,应遵循以下规则 -
公有继承 - 从 public 基类派生类时,基类的 public 成员将成为派生类的 public 成员,而基类的 protected 成员将成为派生类的 protected 成员。基类的 private 成员永远无法从派生类直接访问,但可以通过调用基类的 public 和 protected 成员来访问。
受保护继承 − 从 protected 基类派生时,基类的 public 和 protected 成员将成为派生类的 protected 成员。
私有继承 − 从 private 基类派生时,基类的 public 和 protected 成员将成为派生类的 private 成员。
多重继承
C++ 类可以从多个继承成员使用多重继承的类。多重继承允许一个类从多个基类继承,这意味着派生类可以有多个父类,并从所有基类继承属性和行为。
扩展语法如下:
class derived-class: access baseA, access baseB....
其中 access 是 public、protected 或 private 之一,每个基类都会指定,它们之间用逗号分隔,如上所示。让我们尝试以下示例:
#include <iostream> using namespace std; // 基类 Shape class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // 基类 PaintCost class PaintCost { public: int getCost(int area) { return area * 70; } }; // 派生类 class Rectangle: public Shape, public PaintCost { public: int getArea() { return (width * height); } }; int main(void) { Rectangle Rect; int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // 打印对象的面积。 cout << "Total area: " << Rect.getArea() << endl; // Print the total cost of painting cout << "Total paint cost: $" << Rect.getCost(area) << endl; return 0; }
当编译并执行上述代码时,它会产生以下结果 -
Total area: 35 Total paint cost: $2450