为什么要在 C++ 中初始化静态类变量? [英] Why should I initialize static class variables in C++?
问题描述
在 C 和 C++ 中,所有静态变量默认初始化为零.
In C and C++ all static variables are initialized by default to ZERO.
这不是静态类数据成员的情况.这是为什么?
This is not the case of static class data members. Why is that?
#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;
}
推荐答案
在类范围内,
int MyClass::classVar = 0; // Why I have to init it here?
是一个定义和
static int classVar;
是一个声明,即.承诺变量将在某处定义:您必须只定义一次您声明的变量.
is a declaration, ie. a promise the variable will be defined somewhere: you must define exactly once the variables you declare.
理由是类声明可能包含在多个源文件中.如果它的一部分是一个定义,它会成倍地发生:这是错误的(例外是内联 [成员] 函数).
The rationale is that the class declaration will likely be included in multiple source files. Would a part of it be a definition, it would take place multiply: this is erroneous (exceptions are inline [member] functions).
注意,根据值初始化规则,可以相处
Note that according to value initialization rules, you can get along with
int MyClass::classVar; // Zero-initialized !
作为定义.
在命名空间范围内声明的变量也是定义(除非它们是 extern
限定的):
Variables declared at namespace scope are definitions too (unless they are extern
qualified):
int var;
是一个声明,也是一个定义:如果你把它放在一个标题中并包含在多个翻译单元中,你就会有一个错误(多重定义的符号",或者类似的东西).
is a declaration, and a definition: if you put this into a header and include it in multiple translation units, you have an error ("multiply defined symbol", or something along those lines).
[注意在C++中(而不是在C中),如果上面的var
是const
,它会自动变成static
如果将其放入多包含的标题中,则不会违反单一定义规则.这有点偏离主题,但请随时询问详细信息]
[Note that in C++ (and not in C), if the var
above is const
, it becomes automatically static
and there is no violation of the One Definition Rule should it be put into a multiply included header. This goes slightly off topic, but feel free to ask details]
这篇关于为什么要在 C++ 中初始化静态类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!