1、析构函数
- 成员函数的一种
- 名字与类名相同
- 没有参数与返回值
- 一个类最多只能有一个析构函数
- 对象消亡时自动调用
- 定义类时如果没有写析构函数,则编译器生成缺省析构函数,缺省的析构函数不会进行用户申请的内存释放等清理工作
- 定义了析构函数,则编译器不生成缺省析构函数
2、代码示例
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
class test
{
private:
int id;
public:
test(int i)
{
id=i;
cout<<"constructor"<< id<<" called."<<endl;
}
~test()
{
cout<<"destructor"<< id<<" called."<<endl;
}
} ;
test a=3;
int main()
{
static test b=4;
test array[2]={1,2};
return 0;
}
实验结果:
constructor3 called.
constructor4 called.
constructor1 called.
constructor2 called.
destructor2 called.
destructor1 called.
destructor4 called.
destructor3 called.
从上面结果我们可以看出,析构函数调用顺序与构造函数调用顺序相反,即先被构造的对象,最后被析构。
test a=3;
int main()
{
static test b=4;
{
test b=5;
}//局部作用域
test array[2]={1,2};
return 0;
}
程序结果:
constructor3 called.
constructor4 called.
constructor5 called.
destructor5 called.
constructor1 called.
constructor2 called.
destructor2 called.
destructor1 called.
destructor4 called.
destructor3 called.