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

前端 未结 5 1494
庸人自扰
庸人自扰 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:35

    Why can't other static data members be initialized in the class definition? Was there a specific reason this was forbidden?

    In general, all static objects require a definition, in one single translation unit, so that they have a well-defined address. As a special exception, static, constant, non-volatile class members don't need a definition if their address is not required, and they have a simple enough type that their value can be replaced by a compile-time constant.

    Historically, "simple enough" was defined as an integral or enumeration type; C++11 extends that to include any literal type with a constexpr specifier.

    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?

    They are not declared at the global namespace scope. They are declared and scoped within the class.

    If you mean, why are they defined outside the class definition, that's because there must be only one definition of the static member in the whole program; but the class must be defined in each translation unit that uses it.

提交回复
热议问题