//析构函数在对象的生命周期结束时调用,例如函数内局部对象是在函数结束时调用,堆内存中对象是在delete时调用。
//<span style="font-family: Arial, Helvetica, sans-serif;">构造函数看前一篇。</span>
</pre><pre code_snippet_id="515346" snippet_file_name="blog_20141111_4_5506757" name="code" class="cpp">// PRC TRY.cpp : 定义控制台应用程序的入口点。
//
// PRC TRY.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Demo{
public:
Demo(int a=0,int b=0){cout<<"调用无参构造函数"<<endl;}
Demo(const Demo &x){cout<<"调用拷贝构造函数"<<endl;}
~Demo(){cout<<"调用析构函数"<<endl;}
};
Demo userCode(Demo b){Demo c(b);return c;}
int main(int argc, char* argv[])
{
Demo a,d;
cout<<"---------"<<endl;
d = userCode(a);
cout<<"---------"<<endl;
return 0;
}<pre name="code" class="cpp">
运行结果:
// PRC TRY.cpp : 定义控制台应用程序的入口点。
//
// PRC TRY.cpp : Defines the entry point for the console application.
//
#include<iostream>
using namespace std;
//最好能单步调试,看得更明显
class Test
{
public:
Test()
{
cout<<"Constructor!"<<endl;
}
~Test()
{
cout<<"Destructor!"<<endl;
}
};
int main()
{
Test* pt;
pt = new Test;//此处调用构造函数
delete pt;//调用析构函数
return 0;
}
运行结果: