- #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之前構造;程序結束時析構
全局對象如果分布在不同文件中,則構造順序隨機