D 程式設計 - 建構函式和解構函式



類建構函式

類**建構函式**是類的特殊成員函式,每當建立該類的新的物件時都會執行。

建構函式的名稱與類名完全相同,它沒有任何返回型別,甚至不是void。建構函式對於設定某些成員變數的初始值非常有用。

以下示例解釋了建構函式的概念:

import std.stdio;

class Line { 
   public: 
      void setLength( double len ) {
         length = len; 
      }
      double getLength() { 
         return length; 
      }
      this() { 
         writeln("Object is being created"); 
      }

   private: 
      double length; 
} 
 
void main( ) { 
   Line line = new Line(); 
   
   // set line length 
   line.setLength(6.0); 
   writeln("Length of line : " , line.getLength()); 
}

編譯並執行上述程式碼後,將產生以下結果:

Object is being created 
Length of line : 6 

引數化建構函式

預設建構函式沒有任何引數,但是如果需要,建構函式可以有引數。這有助於您在建立物件時為其分配初始值,如下例所示:

示例

import std.stdio;

class Line { 
   public: 
      void setLength( double len ) { 
         length = len; 
      }
      double getLength() { 
         return length; 
      }
      this( double len) { 
         writeln("Object is being created, length = " , len ); 
         length = len; 
      } 

   private: 
      double length; 
} 
 
// Main function for the program 
void main( ) { 
   Line line = new Line(10.0);
   
   // get initially set length. 
   writeln("Length of line : ",line.getLength()); 
    
   // set line length again 
   line.setLength(6.0); 
   writeln("Length of line : ", line.getLength()); 
}

編譯並執行上述程式碼後,將產生以下結果:

Object is being created, length = 10 
Length of line : 10 
Length of line : 6

類解構函式

**解構函式**是類的特殊成員函式,每當其類的物件超出範圍或每當將delete表示式應用於指向該類物件的指標時都會執行。

解構函式的名稱與類名完全相同,前面加一個波浪號 (~)。它既不能返回值,也不能接受任何引數。解構函式對於在程式退出之前釋放資源(例如關閉檔案、釋放記憶體等)非常有用。

以下示例解釋了解構函式的概念:

import std.stdio;

class Line { 
   public: 
      this() { 
         writeln("Object is being created"); 
      }

      ~this() { 
         writeln("Object is being deleted"); 
      } 

      void setLength( double len ) { 
         length = len; 
      } 

      double getLength() { 
         return length; 
      }
  
   private: 
      double length; 
}
  
// Main function for the program 
void main( ) { 
   Line line = new Line(); 
   
   // set line length 
   line.setLength(6.0); 
   writeln("Length of line : ", line.getLength()); 
}

編譯並執行上述程式碼後,將產生以下結果:

Object is being created 
Length of line : 6 
Object is being deleted
d_programming_classes_objects.htm
廣告