简体   繁体   English

为什么非常量静态成员有多个定义?

[英]Why would a non-constant static member have multiple definitions?

C++ forces the programmer to define a non-constant static member outside the class, and the reason for this that I keep seeing is that if the static member was defined inside the class, this would result in multiple definitions for the static member. C ++强制程序员在类外部定义一个非常量静态成员,我不断看到的原因是如果静态成员是在类中定义的,这将导致静态成员的多个定义。 I understand that having multiple definitions for a static member is bad, but I don't understand where these multiple definitions would even come from. 我知道有一个静态成员的多个定义是坏的,但我不明白这些多个定义甚至会来自何处。 Shouldn't an initialized non-constant static member just go in the data section and that be the only definition? 初始化的非常量静态成员不应该只进入数据部分并且这是唯一的定义吗?

struct Student {

   static int x = 4; // Why would this result in multiple definitions?

};

Also, I read in this other stackoverflow post that const static members are simply inlined into the code wherever it is used: Why can't I have a non-integral static const member in a class? 另外,我在其他stackoverflow文章中读到,const静态成员只是在使用它的地方简单地内联到代码中: 为什么我不能在类中有一个非整数的静态const成员? Is that handled by the preprocessor along with all the other directives? 这是由预处理器和所有其他指令处理的吗? ( I will ask this in another post if needed, but I wasn't sure if it's worthy of a separate post ). (如果需要,我会在另一篇文章中提出这个问题,但我不确定它是否值得单独发帖)。

It would happen because/when your header gets included in multiple "translation units" (think .cpp files). 这会发生是因为/当你的标题被包含在多个“翻译单元”中时(想想.cpp文件)。

Each TU will then contain a copy of the definition. 然后,每个TU将包含该定义的副本。

At link time, they will clash. 在链接时,他们会发生冲突。 (The linker links the objects from each translation unit) (链接器链接每个翻译单元的对象)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM