一个类的构造函数是每当我们创建一个类的新对象时执行的类的一个特殊的成员函数。
构造函数将有完全相同于类的名称,它不具有任何返回类型可言,甚至不是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