Is it possible to initialize a static constant member in a class definition? Please see below for the code,
class foo
{
public:
foo(int p) : m_p(p){}
~foo(){}
private:
int m_p;
};
class bar
{
public:
bar(){}
~bar(){}
public:
static const foo m_foo = foo( 2 ); //is this possible?
};
Many thanks.
Short answer:
No, until the static member is const and is of integral or enumeration type.
Long answer:
$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."
Not for a static data member of class type, as in your example.
9.4.2/2:
The declaration of a static data member in its class definition is not a definition ... The definition for a static data member shall appear in a namespace scope enclosing the member's class definition.
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 name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.
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.