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++静态成员变量及其初始化
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01