#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A(int k)
{
s = k;
cout << k << "A is constructing\n";
}
;
~A()
{
cout << s << "~A\n";
}
int s;
};
void f()
{
cout << "f is running\n";
A s(2);// 优先级4
static A t(3);// 相当于全局对象,优先级2
}
int main(int argc, char **argv)
{
cout << "main is running\n";
A s(1);// 优先级3
f();
cout << "back in main" << endl;
return 0;
}
A t(4);// 全局对象,优先级1
[cpp]
4A is constructing
main is running
1A is constructing
f is running
2A is constructing
3A is constructing
2~A
back in main
1~A
3~A
4~A
局部和静态局部对象(文件作用域)以文本定义顺序为顺序,(类成员属于此种情况)
静态对象在首次定义时构造一次;程序结束析构
全局对象在main之前构造;程序结束时析构
全局对象如果分布在不同文件中,则构造顺序随机
本篇文章来源于 Linux公社网站(www.linuxidc.com) 原文链接:http://www.linuxidc.com/Linux/2012-02/54673.htm