C++ 继承
面向对象编程中最重要的概念之一是继承。继承允许我们根据另一个类来定义一个类,这使得创建和维护应用程序变得更加容易。这也提供了重用代码功能和快速实施时间的机会。
创建类时,程序员可以指定新类继承现有类的成员,而不是编写全新的数据成员和成员函数。这个现有的类称为基类,新的类称为派生类。
继承的思想实现了一种关系。例如,哺乳动物是动物,狗是哺乳动物,因此狗也是动物,等等。
基类和派生类
一个类可以从多个类派生,这意味着它可以从多个基类继承数据和函数。为了定义派生类,我们使用类派生列表来指定基类。类派生列表命名一个或多个基类,并具有以下形式 -
class derived-class: access-specifier base-class
其中 access-specifier 是public、protected或private之一,而 base-class 是先前定义的类的名称。如果未使用访问说明符,则默认情况下它是私有的。
考虑基类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
访问控制和继承
派生类可以访问其基类的所有非私有成员。因此,派生类的成员函数不应访问的基类成员应在基类中声明为私有。
我们可以根据谁可以通过以下方式访问它们来总结不同的访问类型 -
| 使用权 | 民众 | 受保护的 | 私人的 |
|---|---|---|---|
| 同班 | 是的 | 是的 | 是的 |
| 派生类 | 是的 | 是的 | 不 |
| 课外 | 是的 | 不 | 不 |
派生类继承所有基类方法,但以下例外 -
- 基类的构造函数、析构函数和复制构造函数。
- 基类的重载运算符。
- 基类的友元函数。
继承类型
当从基类派生类时,可以通过公共继承、受保护继承或私有继承来继承基类。继承类型由访问说明符指定,如上所述。
我们很少使用受保护或私有继承,但常用公共继承。在使用不同类型的继承时,应用以下规则 -
公共继承- 当从公共基类派生类时,基类的公共成员将成为派生类的公共成员,基类的受保护成员将成为派生类的受保护成员。基类的私有成员永远不能从派生类直接访问,但可以通过调用基类的公共和受保护成员来访问。
受保护的继承- 当从受保护的基类派生时,基类的公共和受保护成员将成为派生类的受保护成员。
私有继承- 从私有基类派生时,基类的公共和受保护成员将成为派生类的私有成员。
多重继承
一个 C++ 类可以从多个类继承成员,下面是扩展语法 -
class derived-class: access baseA, access baseB....
如果访问权限是公共的、受保护的或私有的,并且将为每个基类提供访问权限,并且它们将用逗号分隔,如上所示。让我们尝试下面的例子 -
#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