面向对象编程中最重要的概念之一是继承.继承允许我们根据另一个类定义一个类,这使得创建和维护应用程序变得更容易.这也提供了重用代码功能和快速实现时间的机会.
创建类时,程序员可以指定新类,而不是编写全新的数据成员和成员函数.应该继承现有类的成员.这个现有的类被称为 base 类,新类被称为派生的类.
继承的想法实现是关系.例如,哺乳动物IS-A动物,狗IS-A哺乳动物因此狗IS-A动物等等.
一个类可以从多个类派生,这意味着它可以从多个基类继承数据和函数.为了定义派生类,我们使用类派生列表来指定基类.类派生列表命名一个或多个基类,其格式为 :
class derived-class:access-specifier base-class
其中access-specifier是 public,protected,或 private 之一,base-class是先前定义的类的名称.如果未使用access-specifier,则默认为private.
考虑基类 Shape 及其派生类 Rectangle 如下 :
#include <iostream> using namespace std; // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derived class class Rectangle: public Shape { public: int getArea() { return (width * height); } }; int main(void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total area: " << Rect.getArea() << endl; return 0; }
编译并执行上述代码时,会产生以下结果 :
Total area: 35
派生类可以访问其基类的所有非私有成员.因此,派生类的成员函数不应该可以访问的基类成员应该在基类中声明为私有.
我们可以根据 - 谁可以访问来汇总不同的访问类型它们按以下方式减去;
访问 | public | protected | 私人 |
---|---|---|---|
同一类 | 是 | 是 | 是 |
派生类 | 是 | 是 | 否 |
外部课程 | 是 | 否 | 否 |
派生类使用以下exc继承所有基类方法eptions :
基类的构造函数,析构函数和复制构造函数.
重载运算符
基类的友元函数.
从基类派生类时,可以通过 public,protected 或 private 继承继承基类.继承类型由access-specifier指定,如上所述.
我们几乎不使用 protected 或 private 继承,但是公共继承是常用的.使用不同类型的继承时,应用以下规则 :
公共继承 : 从 public 基类派生类时,基类的 public 成员将成为派生类的 public 成员,并且 protected 基类的成员成为派生类的 protected 成员.基类的私有成员永远不能直接从派生类访问,但可以通过调用 public 和 protected 成员来访问class.
受保护的继承 : 从受保护的基类派生时,基类的公共和受保护的成员变为受保护的派生的成员class.
私人继承 : 从私有基类派生时,基类的公共和受保护成员成为派生的私有成员class.
C ++类可以从多个类继承成员这里是扩展语法 :
class derived-class:access baseA,access baseB ....
访问权限是 public,protected,或 private 之一,并且会为每个基类提供访问权限,并且它们将以逗号分隔如上所示.让我们尝试以下示例 :
#include <iostream> using namespace std; // Base class Shape class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Base class PaintCost class PaintCost { public: int getCost(int area) { return area * 70; } }; // Derived class 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(); // Print the area of the object. 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