问题描述
在C ++ 11和C ++ 14中,为什么我需要 constexpr :
In C++11 and C++14, why do I need constexpr in the following snippet:
class Foo { static constexpr double X = 0.75; };
,但这会产生编译器错误:
whereas this one produces a compiler error:
class Foo { static const double X = 0.75; };
(更奇怪的是)这个编译没有错误?
and (more surprisingly) this compiles without errors?
class Foo { static const double X; }; const double Foo::X = 0.75;
推荐答案
在C ++ 03中,在枚举类型的const积分的静态成员变量的类初始化器中,在C ++ 11中,我们可以使用constexpr初始化类中的文字类型的静态成员。这个限制保留在C ++ 11中的const变量主要是为了兼容性,C ++ 03我们可以从,它说:
In C++03 we were only allowed to provide an in class initializer for static member variables of const integral of enumeration types, in C++11 we could initialize a static member of literal type in class using constexpr. This restriction was kept in C++11 for const variables mainly for compatibility will C++03 we can see this from closed issue 1826: const floating-point in constant expressions which says:
CWG最后将此请求关闭为不是缺陷),基本上说:
CWG ended up closing this request as not a defect(NAD), basically saying:
参考 N1804 9.4.2 [class.static.data] 说:
和草稿C ++ 11标准部分 9.4.2 [class.static.data] 说:
and the draft C++11 standard section 9.4.2 [class.static.data] says:
这在草案C ++ 14标准中是相同的。
this is pretty much the same in the draft C++14 standard.
这篇关于静态类成员的常量表达式初始值为double类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!