C++ C++;11在开关情况下混合使用枚举类和无符号整数将无法编译
为什么这段代码不编译,我能做些什么使它编译C++ C++;11在开关情况下混合使用枚举类和无符号整数将无法编译,c++,c++11,enum-class,C++,C++11,Enum Class,为什么这段代码不编译,我能做些什么使它编译 #include <iostream> using namespace std; enum class myEnum : unsigned int { bar = 3 }; int main() { // your code goes here unsigned int v = 2; switch(v) { case 2: break; cas
#include <iostream>
using namespace std;
enum class myEnum : unsigned int
{
bar = 3
};
int main() {
// your code goes here
unsigned int v = 2;
switch(v)
{
case 2:
break;
case myEnum::bar:
break;
}
return 0;
}
未能在GCC和Clang中构建,在MSVC 2013中工作。枚举类的整个目的是使其成员无法直接与
int
s进行比较,表面上改善了C++11相对于C++03的类型安全性。从enum class
中删除class
,这将编译
引用比亚恩勋爵的话:
(a)enum类
(作用域枚举)是一种enum
,其中枚举数在枚举的作用域内,并且不提供到其他类型的隐式转换
另一种继续使用
enum class
的方法是向myEnum
添加一个表示值为2的新字段。然后可以将unsigned int v
更改为myEnum v
enum class myEnum : unsigned int
{
foo = 2,
bar = 3
};
int main() {
myEnum v = myEnum::foo;
switch(v)
{
case myEnum::foo:
break;
case myEnum::bar:
break;
}
}
您可以简单地使用以下语法:
enum class Test { foo = 1, bar = 2 };
int main()
{
int k = 1;
switch (static_cast<Test>(k)) {
case Test::foo: /*action here*/ break;
}
}
enum类测试{foo=1,bar=2};
int main()
{
int k=1;
开关(静态(k)){
案例测试::foo:/*此处的操作*/break;
}
}
一个使用类和开关大小写的enum示例,这是从另一个类调用enum类的正确方法
class MyClass
{
public:
enum class colors {yellow , blue , green} ;
};
int main ()
{
Myclass::colors c = Myclass::colors::yellow;
switch(c)
{
case Myclass::colors::yellow:
cout <<"This is color yellow \n"
case Myclass::colors::blue:
cout <<"This is color blue\n"
}
return 0 ;
}
class-MyClass
{
公众:
枚举类颜色{黄、蓝、绿};
};
int main()
{
Myclass::colors c=Myclass::colors::yellow;
开关(c)
{
案例Myclass::颜色::黄色:
coutstatic\u cast(2)
强类型枚举是强类型的,并且没有到整数类型的隐式转换。我想:“unsigned int”允许这样做吗?不,这只是意味着枚举将存储在一个无符号的int中。枚举本身仍然是强类型的。我敢说你夸大了“全部用途”。还有另一个原因使用enum class
——将枚举数限制为嵌套的命名空间。嗨,Mike,问题是它为什么不编译以及如何修复.P请编辑您的答案以解决该问题。
class MyClass
{
public:
enum class colors {yellow , blue , green} ;
};
int main ()
{
Myclass::colors c = Myclass::colors::yellow;
switch(c)
{
case Myclass::colors::yellow:
cout <<"This is color yellow \n"
case Myclass::colors::blue:
cout <<"This is color blue\n"
}
return 0 ;
}