Why do non-const, non-int/enum static data members have to be initialized outside the definition?

前端 未结 5 1549
庸人自扰
庸人自扰 2020-12-18 05:07

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

5条回答
  •  渐次进展
    2020-12-18 05:36

    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.

提交回复
热议问题