gpt4 book ai didi

c++ - 表达式中使用的枚举数是否与其枚举的基础类型具有相同的类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:17:35 26 4
gpt4 key购买 nike

当在无范围枚举定义之外使用时,枚举常量的类型是什么?

考虑以下代码:

#include <iostream>

enum modes
{
begin = 0,
end = 1
};

int main()
{
std::cout << std::boolalpha
<< std::is_same<unsigned int, typename std::underlying_type<modes>::type>::value
<< std::endl;
std::cout << sizeof(modes) << std::endl;
std::cout << (-100 + end) << std::endl;
}

这在我的机器上产生:

true
4
-99

现在,如果我只将其他一些枚举器的值从 begin 更改为 2147483648,那么我的输出将变为:

true
4
4294967197

显然,这意味着 end 的类型已经从 int 变成了 unsigned int,甚至底层的 modes 仍然相同(即 unsigned int)。

关于枚举的积分提升是否有一些特殊规则?

最佳答案

来自 C++ 标准(7.2 枚举声明)

  1. ...Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration....

和(4.5积分促销)

3 A prvalue of an unscoped enumeration type whose underlying type is not fixed (7.2) can be converted to a prvalue of the first of the following types that can represent all the values of the enumeration (i.e., the values in the range bmin to bmax as described in 7.2): int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int. If none of the types in that list can represent all the values of the enumeration, a prvalue of an unscoped enumeration type can be converted to a prvalue of the extended integer type with lowest integer conversion rank (4.13) greater than the rank of long long in which all the values of the enumeration can be represented. If there are two such extended types, the signed one is chosen.

关于c++ - 表达式中使用的枚举数是否与其枚举的基础类型具有相同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45091231/

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