D 程式設計 - 繼承



面向物件程式設計中最重要的概念之一是繼承。繼承允許根據另一個類來定義類,這使得建立和維護應用程式更容易。這也提供了重用程式碼功能和加快實現時間的機會。

建立類時,程式設計師無需編寫全新的資料成員和成員函式,而是可以指定新類應該繼承現有類的成員。這個現有類稱為**基類**,新類稱為**派生類**。

繼承的概念實現了“是-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

訪問控制和繼承

派生類可以訪問其基類所有非私有成員。因此,基類成員如果不需要被派生類的成員函式訪問,應該在基類中宣告為私有。

派生類繼承所有基類方法,但以下情況除外:

  • 基類的建構函式、解構函式和複製建構函式。
  • 基類的過載運算子。

多層繼承

繼承可以有多個層次,以下示例展示了這一點。

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
廣告