C++静态成员变量及其初始化

2022-01-18 00:00:00 initialization c++ static-variables


对于 C++ 类中的静态成员变量 - 初始化在类外完成.我想知道为什么?对此有任何逻辑推理/限制吗?或者它是纯粹的遗留实现 - 标准不想更正?


For static member variables in C++ class - the initialization is done outside the class. I wonder why? Any logical reasoning/constraint for this? Or is it purely legacy implementation - which the standard does not want to correct?

我认为在类中进行初始化更直观"且不那么混乱.它还给人以变量的静态和全局性的感觉.例如,如果您看到静态 const 成员.

I think having initialization in the class is more "intuitive" and less confusing.It also gives the sense of both static and global-ness of the variable. For example if you see the static const member.

推荐答案

从根本上说,这是因为静态成员必须在一个翻译单元中定义,以免违反 单一定义规则.如果语言允许类似:

Fundamentally this is because static members must be defined in exactly one translation unit, in order to not violate the One-Definition Rule. If the language were to allow something like:

struct Gizmo
{
  static string name = "Foo";
};

然后 name 将在 #include 的这个头文件的每个翻译单元中定义.

then name would be defined in each translation unit that #includes this header file.

C++ 确实允许您在声明中定义 integral 静态成员,但您仍然必须在单个翻译单元中包含定义,但这只是一种快捷方式,或语法糖.所以,这是允许的:

C++ does allow you to define integral static members within the declaration, but you still have to include a definition within a single translation unit, but this is just a shortcut, or syntactic sugar. So, this is allowed:

struct Gizmo
{
  static const int count = 42;
};

只要 a) 表达式是 const 整数或枚举类型,b) 表达式可以在编译时计算,并且 c) 在某处仍有不违反的定义一定义规则:

So long as a) the expression is const integral or enumeration type, b) the expression can be evaluated at compile-time, and c) there is still a definition somewhere that doesn't violate the one definition rule:

文件:gizmo.cpp

file: gizmo.cpp

#include "gizmo.h"

const int Gizmo::count;

相关文章