建立不同类型对象时,构造函数和析构函数的调用顺序

头文件

#ifndef CONS_DES_H
#define CONS_DES_H
#include<iostream>
class base
{
	public:
		base(int);
		~base();
	private:
		int data;
};
#endif

隐藏源文件:

<span style="color:#330033;">#include "cons_des.h"
#include<iostream>

base::base(int value):data(value)
{
	std::cout<<"Object"<<data<<"constructor";
}
base::~base()
{
	std::cout<<"Object"<<data<<"destructor"<<std::endl;</span><span style="color: rgb(51, 102, 255);">
}</span>

主文件:

<span style="color:#330033;">#include "cons_des.h"
#include<iostream>
using namespace std;
void create();
base first(1);
int main()
{
	cout<<"     (global created before main)"<<endl;
	base second(2);
	cout<<"     (local automatic in main)"<<endl;
	static base third(3);
    cout << "   (local static in main)" << endl;
    create();
    base sixth(6);
    cout<<"(local automatic in main)"<<endl;
}
void create()
{
	base fourth(4);
	 cout << "   (local automatic in create)" << endl;
	 static base fifth(5);
	 cout << "   (local static in create)" << endl;
	 
}</span>

Object1constructor     (global created before main)
Object2constructor     (local automatic in main)
Object3constructor   (local static in main)
Object4constructor   (local automatic in create)
Object5constructor   (local static in create)
Object4destructor
Object6constructor(local automatic in main)
Object6destructor
Object2destructor
Object5destructor
Object3destructor
Object1destructor


--------------------------------
Process exited after 0.924 seconds with return value 0


请按任意键继续. . .

以上程序中,在主程序运行之前,已经建立第一个对象(即全局对象first),主程序运行之后,顺序地建立自动对象second和静态对象third。

接着调用函数create( ),在create( )中建立自动对象fourth和内部静态对象fifth,退出create( )时除静态对象fifth外,删除其它对象并调用它的析构函数,即fourth。

回至主程序后,建立自动对象sixth。

退出主程序时,先删除主程序内的自动对象并调用它们的析构函数,即fourth和second。然后删除内部静态对象并调用它们的析构函数,即second和fifth。最后删除主程序外的全局对象并调用它的析构函数,即first。



猜你喜欢

转载自blog.csdn.net/w3071206219/article/details/52723215
今日推荐