C ++ 11枚举类实例化 [英] C++11 enum class instantiation

查看:522
本文介绍了C ++ 11枚举类实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下形式的枚举类变量实例化,它是编译没有任何警告或错误VS2012:

I've encountered the following form of enum class variable instantiation and it is compiling without any warning or error under VS2012:

UINT32 id;
enum class X {apple, pear, orange};
X myX = X(id);

此外,发送 X(id)一个期望X类型param编译的函数的参数。
我不确定结果总是正确还是只是一个奇怪的编译器行为。

Moreover, sending X(id) as an argument to a function expecting X type param compiled as well. I'm not sure if the result is always correct or it's just a strange compiler behavior.

但是,尝试做 X myX(id); 而不是以上导致编译错误:

However, trying to do X myX(id); instead of the above resulted in compilation error:



错误C2440:'initializing':无法从'UINT32'转换为'X'。
转换为枚举类型需要显式转换(static_cast,C风格的转换或函数式转换)。

error C2440: 'initializing' : cannot convert from 'UINT32' to 'X'. Conversion to enumeration type requires an explicit cast (static_cast,C-style cast or function-style cast).


阅读C ++ 11标准并没有帮助我理解。
因此我有两个关于这个主题的问题:

Reading the C++11 standard didn't help me to understand. So I have 2 questions on this subject:


  1. 可以构建一个枚举类对象, ?

  2. 如果1为true,为什么 X myX(id)无效?

  1. Is it possible to construct an enum class object with integral type as a parameter?
  2. If 1 is true, why X myX(id) doesn't work?


推荐答案

您不是使用该语法构建枚举。而是使用另一种显式转换语法从 UINT32 转换为枚举类X 。例如,可以显式地将一个double转换为一个int,如下所示:

You are not constructing an enum with that syntax. Instead you are using an alternative explicit cast syntax to cast from UINT32 to enum class X. For example it is possible to explicitly cast a double to an int like this:

double p = 0.0;
int f = int(p)

查看这个堆栈溢出post 所有各种铸造语法,你可以在c ++中使用。

See this stack overflow post for all the various cast syntax you can use in c++.

UINT32 id;
enum class X {apple, pear, orange};
X myX = (X)id;

这篇关于C ++ 11枚举类实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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