一.作用
用于完成对象被删除前的一些清理工作。至于完成怎样的清理工
作,由设计者在函数体中实现。
二.调用时间
在对象的生存期结束的时刻,即在删除一个对象前由系统自动调用,然
后再释放此对象所属的空间。
三.默认的析构函数
如果程序中未声明析构函数,编译器将自动产生一个默认的析构函数
规定:
1.是类的公有函数成员,名称由类名前加” ~”构成
2.没有参数,没有返回值
3.一个类中只能定义一个析构函数,不能重载
4.形式: 类名::~类名(){}
5.一般情况下,可以不定义析构函数
但如果类的数据成员中包含指针变量是从堆上进行存储空间
分配的话,需要在析构函数中进行存储空间的回收
四.编写一个代码检验析构函数是否执行
#include <iostream>
#include <cstring>
using namespace std;
class Test
{
private:
int a;
char *str;
public:
Test(int b, char *s) //构造函数
{
a=b; str=new char[strlen(s)+1]; strcpy(str,s); }
void setA(int b) {
a=b; }
void setStr(char *s) {
strcpy(str,s); }
void show () {
cout<<a<<","<<str<<endl; }
Test(const Test& C) {
a=C.a; str=new char[strlen(C.str)+1];
strcpy(str,C.str); }
~Test(){
delete str; cout<<“析构函数”<<endl; } //析构函数//类的数据成员中包含指针变量str是从堆上进行存储空间分配,需要在析构函数中进行存储空间的回收。
};
int main()
{
Test xx(100,"hello");
Test yy(xx);
xx.show(); yy.show();
xx.setA(80); xx.setStr("abc");
xx.show(); yy.show();
return 0;
}
运行结果
100,hello
100,hello
80,abc
100, hello
析构函数
析构函数