析构函数是一个特殊的成员函数,与构造函数相反,与用于初始化对象的构造函数不同,析构函数销毁(或删除)对象。
析构函数语法:
~class_name()
{
//Some code
}
与构造函数类似,析构函数名称应与类名完全匹配。析构函数声明应始终以波形符(~)符号开头,如上面的语法所示。
什么时候析构函数被调用?
在以下情况下,析构函数自动调用:
1)程序完成执行。
2)当包含局部变量的作用域({}括号)结束时。
3)当你调用delete运算符时。
析构函数示例
#include
using namespace std;
class HelloWorld{
public:
//Constructor
HelloWorld(){
cout<<"Constructor is called"< } //Destructor ~HelloWorld(){ cout<<"Destructor is called"< } //Member function void display(){ cout<<"Hello World!"< } }; int main(){ //Object created HelloWorld obj; //Member function called obj.display(); return 0; } 输出: Constructor is called Hello World! Destructor is called 析构函数规则 1)名称应以波形符号(~)开头,并且必须与类名匹配。 2)一个类中不能有多个析构函数。 3)与可以有参数的构造函数不同,析构函数不允许任何参数。 4)他们没有任何返回类型,就像构造函数一样。 5)当你没有在类中指定任何析构函数时,编译器会生成一个默认的析构函数并将其插入到代码中。