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

头文件

#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。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值