Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?
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?
Because that's just how C++ does class members. This is no different than other class members like member functions:
Header file:
namespace example {
// Class declared in header
struct some_class
{
// Member variable
static float example;
// Member function
void DoStuff() const;
};
}
Source file:
namespace example {
// Implement member variable
float some_class::example = 3.14159;
// Implement member function
void some_class::DoStuff() 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…