uacs2024

导航

C++ 类构造函数 & 析构函数

带参数的构造函数

默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值,如下面的例子所示:

 1 #include <iostream>
 2 using namespace std;
 3  
 4 class Line
 5 {
 6    public:
 7       void setLength( double len );
 8       double getLength( void );
 9       Line(double len);  // 这是构造函数
10  
11    private:
12       double length;
13 };
14  
15 // 成员函数定义,包括构造函数
16 Line::Line( double len)
17 {
18     cout << "Object is being created, length = " << len << endl;
19     length = len;
20 }
21  
22 void Line::setLength( double len )
23 {
24     length = len;
25 }
26  
27 double Line::getLength( void )
28 {
29     return length;
30 }
31 // 程序的主函数
32 int main( )
33 {
34    Line line(10.0);
35  
36    // 获取默认设置的长度
37    cout << "Length of line : " << line.getLength() <<endl;
38    // 再次设置长度
39    line.setLength(6.0); 
40    cout << "Length of line : " << line.getLength() <<endl;
41  
42    return 0;
43 }

使用初始化列表来初始化字段

使用初始化列表来初始化字段:

Line::Line( double len): length(len)
{
    cout << "Object is being created, length = " << len << endl;
}

上代码等价于:

Line::Line( double len)
{
    length = len;
    cout << "Object is being created, length = " << len << endl;
}

类的析构函数

类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。

析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 class Line
 6 {
 7    public:
 8       void setLength( double len );
 9       double getLength( void );
10       Line();   // 这是构造函数声明
11       ~Line();  // 这是析构函数声明
12  
13    private:
14       double length;
15 };
16  
17 // 成员函数定义,包括构造函数
18 Line::Line(void)
19 {
20     cout << "Object is being created" << endl;
21 }
22 Line::~Line(void)
23 {
24     cout << "Object is being deleted" << endl;
25 }
26  
27 void Line::setLength( double len )
28 {
29     length = len;
30 }
31  
32 double Line::getLength( void )
33 {
34     return length;
35 }
36 // 程序的主函数
37 int main( )
38 {
39    Line line;
40  
41    // 设置长度
42    line.setLength(6.0); 
43    cout << "Length of line : " << line.getLength() <<endl;
44  
45    return 0;
46 }

执行结果:

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

 

posted on 2024-03-02 13:45  ᶜʸᵃⁿ  阅读(3)  评论(0编辑  收藏  举报