D編程 Constructor & destructor

2021-09-01 11:29 更新

類構(gòu)造函數(shù)

類構(gòu)造函數(shù)是該類的特殊成員函數(shù),只要我們創(chuàng)建該類的新對象 ,該函數(shù)便會執(zhí)行。

構(gòu)造函數(shù)的名稱與類完全相同,沒有任何返回類型,構(gòu)造函數(shù)對于為某些成員變量設置初始值非常有用。

以下示例解釋了構(gòu)造函數(shù)的概念-

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

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

Object is being created 
Length of line : 6 

參數(shù)化構(gòu)造函數(shù)

分配初始值,如以下示例所示-

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

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

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

類析構(gòu)函數(shù)

析構(gòu)函數(shù)的名稱與以波浪號(~)為前綴的類的名稱完全相同,它既不能返回值,也不能采用任何參數(shù),如關(guān)閉文件,釋放內(nèi)存等。

以下示例解釋了析構(gòu)函數(shù)的概念-

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

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

Object is being created 
Length of line : 6 
Object is being deleted


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號