且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C++ 中的类声明中初始化 const 成员

更新时间:2022-01-21 02:14:58

在 C++11 中,非static 数据成员,static constexpr 数据成员,以及 static const 整数或枚举类型的数据成员可以在类声明中初始化.例如

In C++11, non-static data members, static constexpr data members, and static const data members of integral or enumeration type may be initialized in the class declaration. e.g.

struct X {
    int i=5;
    const float f=3.12f;
    static const int j=42;
    static constexpr float g=9.5f;
};

在这种情况下,类 X 的所有实例的 i 成员被编译器生成的构造函数初始化为 5,并且f 成员被初始化为 3.12.static const 数据成员 j 初始化为 42static constexpr 数据成员 g 被初始化为 9.5.

In this case, the i member of all instances of class X is initialized to 5 by the compiler-generated constructor, and the f member is initialized to 3.12. The static const data member j is initialized to 42, and the static constexpr data member g is initialized to 9.5.

由于 floatdouble 不是整数或枚举类型,因此此类成员必须是 constexpr 或非 static 以便允许类定义中的初始化程序.

Since float and double are not of integral or enumeration type, such members must either be constexpr, or non-static in order for the initializer in the class definition to be permitted.

在 C++11 之前,只有 static const 整数或枚举类型的数据成员可以在类定义中具有初始化器.

Prior to C++11, only static const data members of integral or enumeration type could have initializers in the class definition.