Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Gray-Ice

个人博客兼个人网站

这只是一篇备忘博文(虽然我大多数文章的目的也都是备忘)。
定义析构函数时只需要在类名前加上~即可说明这是析构函数,如:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
class Ts
{
int num1 = 0;
int num2 = 0;
public:
~Ts()
{
cout << "This class was deleted." << endl;
}
};

需要注意的是,析构函数不接受任何参数。
那么来演示一下上面定义的类的运行结果,代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;
class Ts
{
int num1 = 0;
int num2 = 0;
public:
Ts() = default;
~Ts()
{
cout << "Ts is going to be delete." << endl;
}
};

int main(void)
{
Ts t1, t2;
return 0;
}

运行结果:

1
2
3
4
╭─fire@butterfly ~/codeSet/CPPCode  
╰─➤ ./a.out
Ts is going to be delete.
Ts is going to be delete.

由于内存回收,所以~Ts()会被调用。
本篇完。

评论



愿火焰指引你