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

为君一笑 提交于 2019-12-11 03:46:28

问题


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

So now I have integer value 15 in a variable of the type Colour.

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?


回答1:


Colour(15) is an expression that creates a temporary (prvalue) instance of the Colour enum, initialized with the value 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).




回答2:


What's happening here is that strongly-typed enums in C++11 are still capable of holding out-of-range values if you explicitly cast or default initialize them. In your example Colour c = Colour(15); is perfectly valid even though Colour only has meaningful values for 1-6.



来源:https://stackoverflow.com/questions/47700057/what-is-happening-when-calling-an-enum-enum-class-with-parentheses-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!