Why do non-const, non-int/enum static data members have to be initialized outside the definition?(为什么非 const、非 int/enum 静态数据成员必须在定义之外进行初始化?)
问题描述
我知道只有静态、常量和 int/enum (pre c++11) 的数据成员才能在类声明中初始化.所有其他静态数据成员必须在全局命名空间范围内定义(即在类定义的主体之外),并且只能在这些定义中初始化".
I understand that only data members which are static, const and int/enum (pre c++11) can be initialized inside the class declaration. "All other static data members must be defined at global namespace scope (i.e. outside the body of the class definition) and can be only initialized in those definitions".
为什么不能在类定义中初始化其他静态数据成员?禁止这样做是否有特定原因?
Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?
如果数据成员是特定于类的,为什么它们在全局命名空间范围内声明,而不是在与其类相关的某个范围内声明?
If the data members are specific to the class, why are they declared at the global namespace scope and not some scope relevant to their class?
推荐答案
为什么不能在类定义中初始化其他静态数据成员?禁止这样做是否有特定原因?
Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?
很可能是因为 C++ 有单独的翻译单元.编译器需要选择一个目标文件,用于放置这些符号的初始化逻辑.将其强制放在特定的源文件中可以使编译器轻松做出决定.
Most likely because C++ has separate translation units. The compiler needs to pick an object file where the initialization logic for those symbols will be placed. Forcing this to be in a specific source file makes that decision easy for the compiler.
如果数据成员是特定于类的,为什么它们在全局命名空间范围内声明,而不是在与其类相关的某个范围内声明?
If the data members are specific to the class, why are they declared at the global namespace scope and not some scope relevant to their class?
因为这正是 C++ 处理类成员的方式.这与成员函数等其他类成员没有什么不同:
Because that's just how C++ does class members. This is no different than other class members like member functions:
头文件:
namespace example {
// Class declared in header
struct some_class
{
// Member variable
static float example;
// Member function
void DoStuff() const;
};
}
源文件:
namespace example {
// Implement member variable
float some_class::example = 3.14159;
// Implement member function
void some_class::DoStuff() const
{
//....
}
}
允许在头文件中初始化静态 const 整数成员有一个特定的例外,因为它允许编译器将它们视为编译时常量.也就是说,您可以使用它们来定义数组的大小或类定义中的其他类似位.
There's a specific exception to allow static const integral members to be initialized in the header because it allows the compiler to treat them as compile-time constants. That is, you can use them to define sizes of arrays or other similar bits in the class definition.
这篇关于为什么非 const、非 int/enum 静态数据成员必须在定义之外进行初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么非 const、非 int/enum 静态数据成员必须在定义之外进行初始化?
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01