目录

C++ Inheritance

面向对象编程中最重要的概念之一是继承。 继承允许我们根据另一个类定义一个类,这使得创建和维护应用程序变得更容易。 这也提供了重用代码功能和快速实现时间的机会。

在创建类时,程序员可以指定新类应该继承现有类的成员,而不是编写全新的数据成员和成员函数。 此现有类称为base类,新类称为derived类。

继承的想法实现了is a关系。 例如,哺乳动物IS-A动物,狗IS-A哺乳动物因此也是狗IS-A动物等等。

基础和派生类

一个类可以从多个类派生,这意味着它可以从多个基类继承数据和函数。 为了定义派生类,我们使用类派生列表来指定基类。 类派生列表命名一个或多个基类,并具有以下形式 -

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

访问控制和继承

派生类可以访问其基类的所有非私有成员。 因此,派生类的成员函数不应该可以访问的基类成员应该在基类中声明为private。

我们可以根据以下方式汇总不同的访问类型 - 谁可以通过以下方式访问它们 -

访问 上市 保护 私人的
Same classyesyesyes
派生类 yesyesno
Outside classesyesnono

派生类继承所有基类方法,但以下情况除外 -

  • 基类的构造函数,析构函数和复制构造函数。
  • 重载基类的运算符。
  • 基类的朋友功能。

继承类型

从基类派生类时,可以通过public, protectedprivate继承继承基类。 继承类型由access-specifier指定,如上所述。

我们几乎不使用protectedprivate继承,但通常使用public继承。 使用不同类型的继承时,应用以下规则 -

  • Public Inheritance - 从public基类派生类时,基类的public成员成为派生类的public成员,基类的protected成员成为派生类的protected成员。 基类的private成员永远不能直接从派生类访问,但可以通过调用基类的public成员和protected成员来访问。

  • Protected Inheritance - 从protected基类派生时,基类的public成员和protected成员将成为派生类的protected成员。

  • Private Inheritance - 从private基类派生时,基类的public成员和protected成员将成为派生类的private成员。

多重继承

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
C++ 重载.下一篇>
↑回到顶部↑
WIKI教程 @2018