声明普通类和类模板的静态数据成员 [英] Declaring static data members of normal class and class template
问题描述
我读取在源文件中定义静态数据成员的原因是因为如果它们在头文件中,并且多个源文件包括头文件,定义将会得到多次输出。我可以看到为什么这将是一个问题的静态const数据成员,但为什么这是静态数据成员的问题?
I read the reason for defining static data members in the source file is because if they were in the header file and multiple source files included the header file- the definitions would get output multiple times. I can see why this would be a problem for the static const data member, but why is this a problem for the static data member?
我不太确定我完全理解为什么有一个问题,如果定义是写在头文件...
I'm not too sure I fully understand why there is a problem if the definition is written in the header file...
推荐答案
我想你很困惑两个东西: static
数据成员和全局变量标记为 static
。
I think you're confusing two things: static
data members and global variables markes as static
.
后者有内部链接,这意味着如果你把它们的定义放在一个头文件中,多个翻译单元 #include
,每个翻译单元将收到这些变量的私有副本。
The latter have internal linkage, which means that if you put their definition in a header file that multiple translation units #include
, each translation unit will receive a private copy of those variables.
默认情况下标记为 const
的全局变量具有内部链接,因此您不需要指定 static
。因此,链接器不会抱怨全局 const
变量或全局非 - const
变量的多个定义标记为 static
,而在其他情况下它会抱怨(因为这些变量会有外部链接)。
Global variables marked as const
have internal linkage by default, so you won't need to specify static
explicitly for those. Hence, the linker won't complain about multiple definitions of global const
variable or of global non-const
variables marked as static
, while it will complain in the other cases (because those variables would have external linkage).
code> static 数据成员,这是C ++ 11标准第9.4.2 / 5段说:
Concerning static
data members, this is what Paragraph 9.4.2/5 of the C++11 Standard says:
static
命名空间范围中的类的数据成员具有外部链接(3.5)。本地类不得有
static
数据成员。
static
data members of a class in namespace scope have external linkage (3.5). A local class shall not havestatic
data members.
这意味着如果你将它们的定义放在一个头文件 #include
d中,你将会得到相应目标文件中相同符号的多个定义完全像非 - const
全局变量),无论它们的 const
- 限定。在这种情况下,您的程序将违反 一种定义规则 。
This means that if you put their definition in a header file #include
d by multiple translation units, you will end up with multiple definitions of the same symbol in the corresponding object files (exactly like non-const
global variables), no matter what their const
-qualification is. In that case, your program would violate the One Definition Rule.
此外, 此Q& A StackOverflow 可以让您更清楚地了解主题。
Also, this Q&A on StackOverflow may give you a clearer understanding of the subject.
这篇关于声明普通类和类模板的静态数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!