main函数执行前与执行后

全局对象、静态全局对象的构造函数在main函数之前执行;
全局对象、静态全局对象的析构函数在main函数之后执行,析构的顺序和构造的顺序相反。

局部对象、静态局部对象的构造函数在main函数之中执行;
局部对象、静态局部对象的析构函数在main函数之后执行,析构的顺序和构造的顺序相反。

注册函数在main函数之后执行,而且注册的顺序和执行的顺序相反。

局部对象的析构函数在注册函数之前执行;
静态局部对象的析构函数在注册函数之后执行。

#include <windows.h>
#include <iostream>
using namespace std;

class GlobalNum
{
public:
    GlobalNum(int num):_num(num)
    {
        cout << "construction : " << _num <<  endl;
        system("pause");
    }
    ~GlobalNum()
    {
        cout << "destruction  : " << _num << endl;
        system("pause");
    }
    void Set(const int &num)
    {
        _num = num;
    }
    int Get()
    {
        return _num;
    }
private:
    int _num;
};
void fn1(void)
{
    cout << "111" << endl;
    system("pause"); 
}

void fn2(void)
{
    cout << "222" << endl;
    system("pause");
}

void fn3(void)
{
    cout << "333" << endl;
    system("pause");
}

void fn4(void)
{
    cout << "444" << endl;
    system("pause");
} 

//全局对象 
GlobalNum num1(100);

//全局对象 
GlobalNum num2(200);

//静态全局对象 
static GlobalNum num3(300);

//静态全局对象 
static GlobalNum num4(400);

int main(void)
{
    cout << endl << "start of main" << endl;

    //局部对象 
    GlobalNum num5(500);

    //局部对象 
    GlobalNum num6(600);

    //静态局部对象 
    static GlobalNum num7(700);

    //静态局部对象 
    static GlobalNum num8(800);

    // 注册需要在 main 函数结束后执行的函数.  
    // 请注意它们的注册顺序和执行顺序
    // 在 main 函数结束后被调用。
    // 调用顺序与注册顺序相反,先注册后执行
    atexit(fn1);
    atexit(fn2);
    atexit(fn3);
    atexit(fn4);

    cout << "end of main" << endl << endl; 

    system("pause");
    return 0;
}

输出结果:

construction : 100
请按任意键继续…
construction : 200
请按任意键继续…
construction : 300
请按任意键继续…
construction : 400
请按任意键继续…

start of main
construction : 500
请按任意键继续…
construction : 600
请按任意键继续…
construction : 700
请按任意键继续…
construction : 800
请按任意键继续…
end of main

请按任意键继续…
destruction : 600
请按任意键继续…
destruction : 500
请按任意键继续…
444
请按任意键继续…
333
请按任意键继续…
222
请按任意键继续…
111
请按任意键继续…
destruction : 800
请按任意键继续…
destruction : 700
请按任意键继续…
destruction : 400
请按任意键继续…
destruction : 300
请按任意键继续…
destruction : 200
请按任意键继续…
destruction : 100
请按任意键继续…

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值