营销网站制作平台有哪些,苏州建设工程信息网站,便宜做网站的公司哪家好,昆明搜索引擎推广析构函数
析构函数于构造函数相对应#xff0c;构造函数是对象创建的时候自动调用的#xff0c;而析构函数就是对象在销毁的时候自动调用的
特点#xff1a;
1#xff09;构造函数可以有多个来构成重载#xff0c;但析构函数只能有一个#xff0c;不能构成重载
2构造函数是对象创建的时候自动调用的而析构函数就是对象在销毁的时候自动调用的
特点
1构造函数可以有多个来构成重载但析构函数只能有一个不能构成重载
2构造函数可以有参数但析构函数不能有参数
3与构造函数相同的是如果我们没有显式的写出析构函数那么编译器也会自动的给我们加上一个析构函数什么都不做如果我们显式的写了析构函数那么将会覆盖默认的析构函数
4在主函数中析构函数的执行在return语句之前这也说明主函数结束的标志是returnreturn执行完后主函数也就执行完了就算return后面还有其他的语句也不会执行的
#include iostream
#include string
using namespace std;class Cperson
{
public:Cperson(){cout Beginning endl;}~Cperson(){cout End endl;}
};int main()
{Cperson op1;system(pause);return 0;
}运行结果
Beginning从这里也可以发现此时析构函数并没有被执行它在system之后return之前执行 指针对象执行析构函数
与栈区普通对象不同堆区指针对象并不会自己主动执行析构函数就算运行到主函数结束指针对象的析构函数也不会被执行只有使用delete才会触发析构函数
#include iostream
#include string
using namespace std;class Cperson
{
public:Cperson(){cout Beginning endl;}~Cperson(){cout End endl;}
};int main()
{Cperson *op2 new Cperson;delete(op2);system(pause);return 0;
}运行结果
Beginning
End在这里可以发现已经出现了End说明析构函数已经被执行也就说明了delete触发了析构函数 临时对象
格式类名()
作用域只有这一条语句相当于只执行了一个构造函数和一个析构函数
除了临时对象也有临时变量例如语句int(12);就是一个临时变量当这句语句执行完了变量也就释放了对外部没有任何影响我们可以通过一个变量来接受这一个临时的变量例如int aint(12);这与int a12;不同后者是直接将一个整型数值赋给变量a而前者是先创建一个临时的变量然后再将这个变量赋给变量a
#include iostream
#include string
using namespace std;class Cperson
{
public:Cperson(){cout Beginning endl;}~Cperson(){cout End endl;}
};int main()
{Cperson();system(pause);return 0;
}运行结果
Beginning
End析构函数的作用
当我们在类中声明了一些指针变量时我们一般就在析构函数中进行释放空间因为系统并不会释放指针变量指向的空间我们需要自己来delete而一般这个delete就放在析构函数里面
#include iostream
#include string
using namespace std;class Cperson
{
public:Cperson(){pp new int;cout Beginning endl;}~Cperson(){delete pp;cout End endl;}private:int *pp;
};int main()
{Cperson();system(pause);return 0;
}malloc、free和new、delete的区别
malloc不会触发构造函数但new可以
free不会触发析构函数但delete可以
#include iostream
#include string
using namespace std;class Cperson
{
public:Cperson(){pp new int;cout Beginning endl;}~Cperson(){delete pp;cout End endl;}private:int *pp;
};int main()
{Cperson *op1 (Cperson *)malloc(sizeof(Cperson));free(op1);Cperson *op2 new Cperson;delete op2;system(pause);return 0;
}运行结果
Beginning
End从结果上来看只得到了一组Beginning、End说明只有一组触发了构造函数和析构函数这一组就是new和delete