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之前的两句话。

本文通过一个具体的C++程序示例,展示了在main函数执行之前程序如何进行初始化,并解释了全局变量的构造函数是如何先于main函数被调用执行的。

被折叠的 条评论
为什么被折叠?



