全局对象、静态全局对象的构造函数在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
请按任意键继续…