我知道只有静态、常量和 int/枚举(c++11 之前)的数据成员才能在类声明中初始化。 “所有其他静态数据成员必须在全局命名空间范围内定义(即在类定义的主体之外)并且只能在这些定义中初始化”。
为什么不能在类定义中初始化其他静态数据成员?是否有具体原因禁止这样做?
如果数据成员特定于类,为什么它们在全局命名空间范围内声明,而不是在与其类相关的某些范围内声明?
最佳答案
Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?
很可能是因为 C++ 有独立的翻译单元。编译器需要选择一个目标文件,其中将放置这些符号的初始化逻辑。强制将它放在特定的源文件中可以使编译器轻松做出决定。
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++ 处理类成员的方式。这与成员函数等其他类成员没有什么不同:
头文件:
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
{
//....
}
}
允许在 header 中初始化静态常量整数成员是一个特定的异常(exception),因为它允许编译器将它们视为编译时常量。也就是说,您可以使用它们来定义数组的大小或类定义中的其他类似位。
关于c++ - 为什么非 const、非 int/enum 静态数据成员必须在定义之外初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15167254/