C ++中的静态变量 [英] Static variables in C++
问题描述
我想知道一个头文件中的静态变量与一个类中声明的变量之间的区别。当在头文件中声明静态变量时,其范围限于.h文件或所有单位。通常静态变量在.cpp文件中初始化时在类中声明吗?所以这意味着静态变量的作用域限于2个编译单元?
当我回答你的问题,
当在头文件中声明静态变量时,它的作用域限于.h文件
没有头文件范围这样的东西。将头文件包含到源文件中。翻译单元是源文件,包括头文件中的文本。
因此,在头文件中声明的静态变量是类似于
因为声明一个变量 static
这意味着内部链接,每个翻译单元 #include
获取其自己,个别变量(在翻译单元之外不可见) 。这通常不是你想要的。
我想知道头文件中的静态变量和类
在类声明中, static
这个成员变量;即,你可能有数百个这种类型的对象,但只要这些对象中的一个引用 static
(或类)变量,它对所有对象都是相同的值。您可以将其视为类全局。
通常,静态变量在.cpp文件中初始化?
是,一个(且只有一个)必须初始化类变量。
这意味着静态变量作用域限于2个编译单元?
< blockquote>
正如我所说:
- 标题不是编译单元,
static
表示完全不同的内容,取决于上下文。
全局
static
将范围限制到翻译单位。
$ b $ p 我希望这有助于。
$ b $ bPS:检查Chubsdad答案的最后一段,关于如何不使用C ++中的
static
,但是匿名命名空间。 (因为他是对的;-))I would like to know what is the difference between static variables in a header file vs declared in a class. When static variable is declared in a header file is its scope limited to .h file or across all units. Also generally static variable is initialized in .cpp file when declared in a class right? So that does mean static variable scope is limited to 2 compilation units?
解决方案Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.
When static variable is declared in a header file is its scope limited to .h file or across all units.
There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.
As such, a static variable declared in a header file is like a static variable in each individual source file.
Since declaring a variable
static
this way means internal linkage, every translation unit#include
ing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.I would like to know what is the difference between static variables in a header file vs declared in a class.
In a class declaration,
static
means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to thestatic
(or "class") variable, it's the same value for all objects. You could think of it as a "class global".Also generally static variable is initialized in .cpp file when declared in a class right ?
Yes, one (and only one) translation unit must initialize the class variable.
So that does mean static variable scope is limited to 2 compilation units ?
As I said:
- A header is not a compilation unit,
static
means completely different things depending on context.Global
static
limits scope to the translation unit. Classstatic
means global to all instances.I hope this helps.
PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use
static
in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )这篇关于C ++中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!