开发者

Is it possible to initialize static const member object in a class in C++?

开发者 https://www.devze.com 2023-01-23 19:48 出处:网络
Is it possible to initialize a static constant member in a class definition? Please see below for the code,

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(){}

   pub开发者_如何学Pythonlic:
     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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号