C++ static member variable and its initialization(C++静态成员变量及其初始化)
问题描述
对于 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 #include
s 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;
这篇关于C++静态成员变量及其初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++静态成员变量及其初始化


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01