目录

D编程 - 继承(Inheritance)

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

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

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

D中的基类和派生类

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

class derived-class: base-class

考虑一个基类Shape及其派生类Rectangle ,如下所示 -

import std.stdio;
// 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: Shape { 
   public: 
      int getArea() { 
         return (width * height); 
      } 
}
void main() { 
   Rectangle Rect = new Rectangle();
   Rect.setWidth(5); 
   Rect.setHeight(7); 
   // Print the area of the object. 
   writeln("Total area: ", Rect.getArea()); 
} 

编译并执行上述代码时,会产生以下结果 -

Total area: 35

访问控制和继承

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

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

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

多级继承

继承可以是多个级别,它在以下示例中显示。

import std.stdio;
// 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: Shape {
   public:
      int getArea() {
         return (width * height); 
      }
}
class Square: Rectangle {
   this(int side) {
      this.setWidth(side); 
      this.setHeight(side); 
   }
}
void main() {
   Square square = new Square(13);
   // Print the area of the object.
   writeln("Total area: ", square.getArea());
}

编译并执行上述代码时,会产生以下结果 -

Total area: 169
↑回到顶部↑
WIKI教程 @2018