为什么必须在类中初始化的非整型静态数据成员是constexpr? [英] Why must non-integral static data members initialized in the class be constexpr?
问题描述
在类定义中初始化的静态积分数据成员可以声明为 const
或 constexpr
,但非整数静态在类定义中初始化的数据成员必须 constexpr
:
Static integral data members initialized in the class definition may be declared const
or constexpr
, but non-integral static data members initialized in the class definition must be constexpr
:
class MyClass {
static const int w = 5; // okay
static constexpr int x = 5; // okay
static const float y = 1.5; // error!
static constexpr float z = 1.5; // okay
};
有没有人知道为什么不允许y的声明?
Does anybody know why the declaration for y is not permitted? The part of the Standard making it illegal is 9.4.2/3, but why is it illegal?
推荐答案
在C ++ 11之前,您无法在类声明中初始化非积分/枚举类型的静态成员(但您可以在类声明之外)。管理 constexpr
的规则带有前进,但允许你在类声明中使用 constexpr
来初始化它不需要像下面的代码):
Prior to C++11, you could not initialize static members of non-integral/enumeration types in the class declaration (but you can outside of the class declaration). The rule governing constexpr
carries that forward, but allows you to initialize it using constexpr
in the class declaration (so you don't need code like the following anymore):
struct A
{
static const float pi;
};
const float A::pi = 3.1415;
这个规则的一个副作用是简化你的类结构而不是让它丑陋
One of the side effects of this rule was to simplify your class structure instead of making it ugly (like the above code).
在C ++ 11添加 constexpr
是标准没有指定如何实现浮点(它留给处理器/架构 - 例如,当你说 float x = 1.6f
时,实际上是 1.6000000000024
在大多数系统上)。
One of the reasons why this was the case prior to C++11's addition of constexpr
was the standard did not specify how floating points were to be implemented (it is left to the processor/architecture - for example, when you say float x = 1.6f
, it is actually 1.6000000000024
on most systems).
这篇关于为什么必须在类中初始化的非整型静态数据成员是constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!