gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:39:43 25 4
gpt4 key购买 nike

如果我尝试编译下面的代码,它会给我错误“枚举值对于基础类型‘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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com