析构函数用于完成类释放前的清理工作,由C++自动调用。
同构造函数,析构函数名为类名称前面加上~符号。析构函数没有返回值也没有参数列表。每个类只有一个析构函数。若没有添加析构函数,C++提供默认的析构函数,但什么也不做。
例:定义一个字符串,在构造函数里创建动态字符数组,在析构函数里释放字符数组,并根据索引获得某个索引的字符。
#include <iostream>
using namespace std;
class STR {
private:
char* pvalue;
int ncount;
public:
STR(char* str)
{
ncount = strlen(str);
pvalue = new char[ncount + 1];
strcpy_s(pvalue, ncount+1,str);
cout << "动态创建数组!" << endl;
}
~STR()
{
delete[] pvalue;
pvalue = NULL;
cout << "动态创建的字符数组已被释放!" << endl;
}
char getvalue(int index)
{
if (index<0 || index>ncount)
return '\0';
else
return pvalue[index];
}
};
int main()
{
char s[] = "hello,world!";
STR ss(s);
cout << ss.getvalue(7) << endl;
return 0;
}
程序运行结果如图: