构造函数和析构函数

类的构造函数:

一个类的构造函数是每当我们创建一个类的新对象时执行的类的一个特殊的成员函数。

构造函数将有完全相同于类的名称,它不具有任何返回类型可言,甚至不是void。构造函数可以是非常有用的为某些成员变量设置初始值。

下面的例子说明了构造函数的概念:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

参数化构造函数:

默认构造函数没有任何参数,但如果需要,构造函数可以有参数。这可以帮助您在其创建为显示在下面的例子中,初始值分配给某个对象时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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表达式应用到一个指针,指向该类的对象类的一个特殊成员函数。

析构函数将有完全相同的名称作为类的前缀与符号(〜),它可以既不返回一个值,也不能带任何参数。析构函数可以是走出来的程序如关闭文件,释放内存等前释放资源非常有用的

下面的例子说明了析构函数的概念:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3