- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
标准在 7.2/5 [dcl.enum]
中说:
If the underlying type is not fixed, the type of each enumerator prior to the closing brace is determined as follows:
(5.1) — If an initializer is specified for an enumerator, the constant-expression shall be an integral constant expression (5.20). If the expression has unscoped enumeration type, the enumerator has the underlying type of that enumeration type, otherwise it has the same type as the expression.
(5.2) — If no initializer is specified for the first enumerator, its type is an unspecified signed integral type.
(5.3) — Otherwise the type of the enumerator is the same as that of the preceding enumerator unless the incremented value is not representable in that type, in which case the type is an unspecified integral type sufficient to contain the incremented value. If no such type exists, the program is ill-formed.
因此,5.1
和 5.2
涵盖了以下所有情况:
I. enum A { x = 4 };//案例 1,指定了初始化器
II. 枚举 B { x, y };//情况 2,未指定初始化器。
三.
enum C { x = 5 };
enum D { y = x }; // case 1, y had unscoped enumeration type.
四.
enum struct C { x = 5 };
enum D { y = 0, x = C::x }; // even integral constant expression must have integral
// or unscoped enumeration type, not 'C
我想看看 5.3
的实际情况。为什么 case IV
连编译都没有?
最佳答案
将作用域枚举引入语言的全部意义在于防止隐式转换为基础类型。因此,在您失败的示例中,无法从 C::x
隐式转换为 D
的基础类型是什么整数类型。
添加适当的转换,您的代码即可编译。
#include <type_traits>
enum struct C { x = 5 };
enum D
{
y = 0,
x = static_cast<std::underlying_type<C>::type>(C::x)
};
关于c++ - 具有非固定类型的枚举的初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27597163/
我是一名优秀的程序员,十分优秀!