在C ++中用括号调用枚举/枚举类时会发生什么? [英] What is happening when calling an enum/enum class with parentheses in C++?

查看:98
本文介绍了在C ++中用括号调用枚举/枚举类时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个有点奇怪的问题,但是我真的不知道该怎么表达。

This is maybe a bit weird question, but I really don't know how to phrase it better than this.

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

I just discovered that I can do the following:

#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;
}

现在我在类型<$ c的变量中有整数值15 $ c>颜色。

这里到底发生了什么?是工作中的某种枚举构造函数吗?据我所知,整数值15不会进行枚举,它仅存储在变量 c 中。为什么这样的事情首先有用-创建枚举中不存在的值?

What exactly is happening here? Is that some kind of enum "constructor" at work? As far as I know, integer value 15 is not put into enumeration, it is stored just in variable c. Why would something like that be useful, in the first place - to create a value that doesn't exist in enum?

推荐答案

Colour(15)是一个表达式,可创建 Colour (prvalue)实例。 >枚举,其初始值为 15

Colour(15) is an expression that creates a temporary (prvalue) instance of the Colour enum, initialized with the value 15.

颜色c =颜色(15); 初始化一个新变量 c 颜色类型的c $ c>。等效于颜色c(15)

Colour c = Colour(15); initializes a new variable c of type Colour from the previously-explained expression. It is equivalent to Colour c(15).

这篇关于在C ++中用括号调用枚举/枚举类时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆