clsaa Car
{public:Car(){
cout<<" construct "<<endl;}~Car(){
cout<<" destruct "<<endl;}};
1、栈上的局部对象
intmain(){
cout<<"main begin"<<endl;
Car Audi;
cout<<"main end"<<endl;return0;}
打印结果:
main begin
construct
main end
destruct
在声明Car的实例Audi时调用构造函数,打印construct。
Audi离开作用域时调用析构函数,打印destruct。
2、全局对象
Car BMW;intmain(){
cout<<"main begin"<<endl;
cout<<"main end"<<endl;return0;}
打印结果:
construct
main begin
main end
destruct
在进入main函数之前调用构造函数,打印construct。
在离开main函数之后调用析构函数,打印destruct。
3、堆对象
Car* BMW;intmain(){
cout <<"main begin"<< endl;
BMW =new Car;delete BMW;
cout <<"main end"<< endl;return0;}
打印结果:
main begin
construct
destruct
main end