更新时间:2022-05-28 00:16:59
在C ++ 11中,非 - 静态
数据成员, 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;
};
在这种情况下, i
编译器生成的构造函数将 X
的所有实例初始化为 5
, f
成员初始化为 3.12
。 static const
数据成员 j
初始化为 42
并将 static 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
.
由于 float
和 double
或枚举类型,这些成员必须是 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.