D編程 繼承

2021-09-01 10:48 更新

面向?qū)ο缶幊讨凶钪匾母拍钪皇抢^承,繼承允許使用一個類繼承另一個類,這樣就可以直接調(diào)用父類的公共函數(shù)或變量,這使得維護變得更加容易。

基類和子類

子類通過":"冒號來實現(xiàn)繼承基類。

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()); 
} 

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

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());
}

編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-

Total area: 169


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號