简体   繁体   中英

C++ standard for defining public variable static const integer

Where should I define a static const integer member variable in c++, in the header file where the class it is defined or in a cpp file?

It complies in both situation, If I let the definition inside the header file and If I move the definition in a cpp file, but which is the c++ standard?

Here is a full quote from the C++ Standard about constant static members:

If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignmentexpression is a constant expression (5.19). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer .

So if a const static member is not ODR-used then its definition outside the class is not required.

Note: by the way in this context it is unimportant whether a const static member is public or not.

You have to define your static member outside the class definition and provide the initailizer there.

For Standard method first do something like this

Declare static variable in header file

class Something
{
public:
    static const int s_nValue;
};

On top of cpp file initialize it like

const int Something::s_nValue = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM