在 C++ 中调用带括号的 enum/enum class 时发生了什么?

What is happening when calling an enum/enum class with parentheses in C++?

这个问题可能有点奇怪,但我真的不知道怎么表达比这更好。

我刚刚发现我可以做到以下几点:

#include <iostream>

enum class Colour  // also works with plain old enum
{
    Red = 1,
    Green,
    Blue,
    Yellow,
    Black,
    White
};

int main()
{
    Colour c = Colour(15);  // this is the line I don't quite understand

    std::cout << static_cast<int>(c) << std::endl;  // this returns 15

    return 0;
}

所以现在我在 Colour.

类型的变量中有整数值 15

这里究竟发生了什么?那是某种枚举 "constructor" 在起作用吗?据我所知,整数值 15 没有放入枚举中,它只存储在变量 c 中。为什么这样的东西会有用,首先 - 创建枚举中不存在的值?

Colour(15) 是一个表达式,它创建 Colour 枚举的临时 (prvalue) 实例,用值 15 初始化。

Colour c = Colour(15); 从前面解释的表达式中初始化一个类型为 Colour 的新变量 c。相当于Colour c(15).

这里发生的事情是,如果您显式强制转换或默认初始化它们,C++11 中的强类型枚举仍然能够保存超出范围的值。在您的示例中,Colour c = Colour(15); 是完全有效的,即使 Colour 仅对 1-6 具有有意义的值。