definition of static const outside the class definition

前端 未结 1 1983
谎友^
谎友^ 2020-12-20 21:50

Should we define a static const member outside of the class definition even if it is initialised inside the class?

#include  
us         


        
相关标签:
1条回答
  • 2020-12-20 22:46

    You are defining the static memberperiod by writing const int abc::period;. You are allowed to provide an in class initializer for static const member of a class but that's not definition, but that's merely a declaration.

    9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

    Your code compiles even without the definition because you are not taking the address of the static member. Bjarne Stroustrup mentions in the C++-FAQ here that You can take the address of a static member if (and only if) it has an out-of-class definition

    0 讨论(0)
提交回复
热议问题