C++程序我們一般寫程序都知道,是從main開始執行,不過,也有例外,比如以下這段程序
#include <iostream>
#include <stdlib.h>
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(int argc, char *argv[])
{
cout << "Entering main()!" << endl;
cout << "Leaving main()!" << endl;
system("PAUSE");
return 0;
}
運行結果如下:

由於a是全局變量,所以會在main之前執行,所以會調用其構造函數,輸出main之前的兩句話。