codecamp

D编程 Constructor & destructor

类构造函数

类构造函数是该类的特殊成员函数,只要我们创建该类的新对象 ,该函数便会执行。

构造函数的名称与类完全相同,没有任何返回类型,构造函数对于为某些成员变量设置初始值非常有用。

以下示例解释了构造函数的概念-

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

类析构函数

析构函数的名称与以波浪号(~)为前缀的类的名称完全相同,它既不能返回值,也不能采用任何参数,如关闭文件,释放内存等。

以下示例解释了析构函数的概念-

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编程 Class access modifiers
D编程 The this pointer in D
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }