#include <iostream> #include <cstdlib>
using namespace std;
class A {
public:
A() { cout << "I come here before main()!" << endl; f(); }
static void f() { cout << "I come here before main() too!" << endl; }
};
static A a; // 全局靜態物件
int main() {
cout << "Entering main()!" << endl;
cout << "Leaving main()!" << endl;
system("PAUSE");
return 0;
}
I come here before main()!
I come here before main() too!
Entering main()!
Leaving main()!
C++ 標準規定:命名空間作用域的靜態/全局物件在 main 進入前完成構造。static A a; 觸發建構函數,故輸出先於 main。同理,析構函數在 main 返回後、程序退出前執行。
init() 可控啟動。