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();
// 设置line长度
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 函数
void main( ) {
Line line = new Line(10.0);
// 得到初始设定的长度。
writeln("Length of line : ",line.getLength());
// 再次设置line长度
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 函数
void main( ) {
Line line = new Line();
// 设置line长度
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.html

