在C和C++中,所有静态变量默认初始化为零。为什么要在C++中初始化静态类变量?
这不是静态类数据成员的情况。这是为什么?
#include <iostream>
using namespace std;
int var;
class MyClass
{
public:
static int classVar;
};
int MyClass::classVar = 0; // Why I have to init it here?
int main(void)
{
cout << ::var << endl; // this is initalized to ZERO by default
static int var;
cout << var << endl; // and this also is initalized to Zero
cout << MyClass::classVar << endl;
return 0;
}
您不确定** var **是否已初始化为0.可能,有时很可能,但不确定。 –
@AlessandroPezzato:实际上,在执行动态初始化之前,标准显式地为所有全局变量清零内存......除了受字面值影响的内置函数,我认为可以直接影响(在因为它是不可观测的。 –