简体   繁体   English

是否可以在C ++中的类中初始化静态const成员对象?

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

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. 否,直到静态成员为const且为整数或枚举类型为止。

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." $ 9.4.2 / 4-“如果静态数据成员为const整型或const枚举类型,则其在类定义中的声明可以指定一个常量初始化器,该初始化器应为整数常量表达式(5.19)。在这种情况下,该成员可以出现在整数常量表达式中。如果在程序中使用了该成员,则该成员仍应在命名空间范围内定义,并且该命名空间范围定义不应包含初始化程序。”

Not for a static data member of class type, as in your example. 如您的示例所示,不适用于类类型的静态数据成员。

9.4.2/2: 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: 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). 如果静态数据成员是const整数或const枚举类型,则其在类定义中的声明可以指定一个常量初始化器,该初始化器应为整数常量表达式(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. 如果程序中使用了该成员,则该成员仍应在名称空间范围内进行定义,并且名称空间范围定义不应包含初始化程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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