c++ - 枚举基础类型与普通类型

标签 c++ c++11 enums

如果我尝试编译下面的代码,它会给我错误“枚举值对于基础类型‘char’来说太大了”

enum class Status:char{one=126,two=127,three=128};
Status s = Status::three;

但是,如果我执行以下代码,编译器不会给我任何错误,并默默地忽略字符上限已越过

char x = 128;

那么编译器不检查普通数据类型而不检查枚举基础类型的范围有什么具体原因吗。

最佳答案

C++11 引入了对“缩小转换”的限制以及允许和不允许的限制。隐藏在 5.19§3 中的是一个描述“转换后的常量表达式”并特别排除缩小转换的子句,然后指出此类表达式可以用于 [...] 枚举器初始值设定项。因此,你不能这样做:

enum class Foo : char { one = 128 };
unsigned char uc1 = {-1};

但你可以做到

enum class Foo : char { one = (char)128 };
unsigned char uc1 = -1;

5.19 [expr.const] §3

[...] A converted constant expression of type T is an expression, implicitly converted to a prvalue of type T, where the converted expression is a core constant expression and the implicit conversion sequence contains only user-defined conversions, lvalue-torvalue conversions (4.1), integral promotions (4.5), and integral conversions (4.7) other than narrowing conversions (8.5.4). [ Note: such expressions may be used in new expressions (5.3.4), as case expressions (6.4.2), as enumerator initializers if the underlying type is fixed (7.2), as array bounds (8.3.4), and as integral or enumeration non-type template arguments (14.3). —end note ]

关于c++ - 枚举基础类型与普通类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38602032/

相关文章:

c++ - 具有多个非可选参数的转换构造函数看起来如何,为什么有意义?

c++ - 在模板类中重载下标运算符

c++ - 在 Visual Studio 2017 中使用函数从 main 创建和初始化数组

c++ - 分离的线程在退出时崩溃

java - (java)如果枚举是静态的 - 如何在我的代码中创建另一个实例(使用 DB40)?

ios - 如何在Xcode,Swift中拖放枚举?

unit-testing - 如何测试枚举类型?

C++如何将字符串分配为十六进制

c++ - 如何在 std::vector 中找到项目的 vector

c++ - 我如何使用可变参数模板产生默认参数的效果