什么是析构函数?
目录:
1.概念
2.特点
3.举例
概念:
什么是析构函数呢?
对要销毁的对象中的资源进行清理工作。
特点:
1.析构函数的函数名是类名前加“~”。
2.无参数无返回类型。
3.一个类只有一个析构函数。
4.对象生命周期结束时,C++编译器会自动调用析构函数。
5. 析构函数不能重载。
6. 如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,比如Date类;有资源申请时,一定要写,否则会造成资源泄漏,比如Stack类。
举例:
#include<iostream>
using namespace std;
class Time
{
public:
~Time()
{
cout << "~Time()" << endl;
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
private:
// 基本类型(内置类型)
int _year = 1970;
int _month = 1;
int _day = 1;
// 自定义类型
Time _t;
};
int main()
{
Date d;
return 0;
}