本文转载于菜鸟教程
类的构析函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。
构析函数的名称与类的名称是完全相同的,只是在前面加了个波浪号~
作为前缀,它不会返回任何值,也不能带有任何参数。构析函数的作用是当对象过期时,完成相应的清理工作,比如关闭文件和释放内存等!
实例代码如下,
#include <iostream>
using namespace std;
class Line
{
public:
Line() { cout << "Object is being created!" << endl; } //这是类Line的构造函数
~Line() { cout << "Object is being deleted!" << endl; } //这是类Line的析构函数
void setLength(double len) { length = len; }
double getLength() { return length; }
private:
double length;
};
int main()
{
Line line;
line.setLength(6.0);
cout << "Length of line: " << line.getLength() << endl;
return 0;
}
代码输出为,
Object is being created!
Length of line: 6
Object is being deleted!