C++构造方法和析构方法:
首先我们先写一个类,在类里写我们所需要的析构和构造方法:
class point {
public :
point(){
cout << "create a project" << endl;
};//构造方法
~point(){
cout << "delete a project" << endl;
}//析构方法
};
当我们使用new关键字时,构造方法就被执行了。
int main()
{
point *p = new point();
return 0;
}
而输出的结果也就是create a project;
而当我们使用与new所相对应的delete的关键字时,析构方法就被执行了。
int main()
{
point *p = new point();
delete p;
return 0;
}
输出的结果就是:
create a project
delete a project
当我们在主程序中直接定义个值对象而不是个指针时。
它有构造也有析构。
int main()
{
// point *p = new point();
// delete p;
point p;
return 0;
}
它的输出结果是:
create a project
delete a project
现在我们就来看看析构函数是什么时候被执行的。
#include <iostream>
using namespace std;
class point {
public :
point(){
cout << "create a project" << endl;
};//构造方法
~point(){
cout << "delete a project" << endl;
}//析构方法
};
void run_point(){
point p;
}
int main()
{
// point *p = new point();
// delete p;
run_point();
cout << "the end" << endl;
return 0;
}
当我们这样写时,它的输出结果就是:
create a project
delete a project
the end
当我们在run_point中加上:
void run_point(){
{
point p;
}
cout << 1 << endl;
}
此时它的输出结果就是:
create a project
delete a project
1
the end
而当我把run_point中的大括号删掉后:
void run_point(){
// {
point p;
// }
cout << 1 << endl;
}
它的结果就是:
create a project
1
delete a project
the end
由此我们就可以得出结论了。析构函数是在构造方法全部执行完后,也就是那个代码块执行完后,就会执行析构函数。
PS:不可碌碌无为。