在C ++中用括号调用枚举/枚举类时会发生什么? [英] What is happening when calling an enum/enum class with parentheses in 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屋!