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

标签 c++ enums enumeration enumerator integer-promotion

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

考虑以下代码:

#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/

相关文章:

c++ - std::sort 在第二个元素没有比较器的对上

c - 为什么枚举值可以有很大的 (>int) 值?

arrays - 在 Swift 中对 Array 调用 .count 时分配计数变量

ios - 如何阻止 NSSet 在其他地方被枚举时发生变异?

java - 在 Java 枚举类型中使用 +

java - 关于java中枚举的两个问题

c++ - 为什么派生类虚函数可以调用基类虚函数?编译器如何实现?

c++ - 服务器断开连接时发送到套接字

c++ - 如何在没有互联网连接的计算机上安装 MinGW?

c# - 在中间添加枚举