【问题标题】:What is happening when calling an enum/enum class with parentheses in C++?在 C++ 中调用带括号的枚举/枚举类时会发生什么?
【发布时间】:2017-12-07 16:57:44
【问题描述】:

这可能是一个有点奇怪的问题,但我真的不知道如何更好地表达它。

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

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

这里到底发生了什么?那是某种枚举“构造函数”吗?据我所知,整数值 15 没有放入枚举中,它只是存储在变量c 中。首先,为什么这样的东西会有用——创建一个枚举中不存在的值?

【问题讨论】:

  • 这只是编写 C 风格演员表 (Colour)15 的另一种方式。

标签: c++ c++11 enums enum-class


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • Colour 仅具有 1-6 的 named 值。这并不意味着其他值没有意义,只是它们没有名称。枚举的一个常见用途是定义位掩码:enum mask { read = 1, write = 2, hidden = 4 }; 现在mask(read+write) 的值为 3,这意味着我们正在谈论的任何内容都可以读写。
    猜你喜欢
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多