【C++ 筆記】解構子(Destructors) - part 18.5

很感謝你點進來這篇文章。

你好,我並不是什麼 C++、程式語言的專家,所以本文若有些錯誤麻煩請各位鞭大力一點,我極需各位的指正及指導!!本系列文章的性質主要以詼諧的口吻,一派輕鬆的態度自學程式語言,如果你喜歡,麻煩留言說聲文章讚讚吧!

解構子(Destructors)

這 18.5 part 是來補全前面建構子只講到一點的解構子,由於解構子的概念並未像建構子那麼複雜,所以只需要 0.5 part 的時間來學習XD。

解構子(Destructor),又名為析構函數,同於建構子是個特殊的成員函數,在當物件的作用域結束時,編譯器會呼叫此函數。

Destructor 可釋放類別中的物件先前使用的所有記憶體,可避免記憶體洩漏與資源浪費的情形發生。

:::success
解構子名稱與類別名稱相同,但是需要加上波浪符號(~)在最前面,以示為解構子。
:::

1
2
3
4
5
6
class ClassName {
public:
~ClassName() {
// Body of Destructor
}
};

以下是個範例:

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
39
40
41
42
43
44
45
46
#include <iostream>

using namespace std;

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // 這是建構子的宣告方式
~Line(); // 這是解構子的宣告方式

private:
double length;
};

// 成員函數定義,包含建構子
Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}

void Line::setLength( double len )
{
length = len;
}

double Line::getLength( void )
{
return length;
}
// 程式之主函數
int main( )
{
Line line;

// 設定長度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}

來源:https://www.runoob.com/cplusplus/cpp-constructor-destructor.html

輸出結果:

1
2
3
Object is being created
Length of line : 6
Object is being deleted

參考資料

C++ Classes and Objects - GeeksforGeeks

C++ 类构造函数 & 析构函数 | 菜鸟教程