析构函数
析构函数
作用:清理工作,比如new给成员分配了空间,析构函数可以释放掉,在构造函数中打开文件,在析构函数中释关闭文件
形式:~类名(),不可进行重载,类中会自动生成一个默认析构函数,该析构函数不做任何处理

#include <iostream>
using namespace std;
class Stu
{
public:
Stu()
{
age = 10;
pp = new int(10);
cout << "执行了构造函数" << endl;
}
Stu(int i)
{
age = i;
pp = new int(10);
cout << "执行了构造函数" << endl;
}
~Stu()
{
cout << "执行了析构函数" << endl;
}
private:
int age;
int* pp;
};
int main()
{
Stu* stu = new Stu();//触发构造函数
delete stu;//触发析构函数
Stu(12);//临时对象,触发了构造函数之后,紧接触发析构函数
Stu stu1(20);//触发构造函数,作用域为函数体,函数结束之后触发构造函数
}

new malloc和free delete区别

本文使用 mdnice 排版