如何在 C++ 中将 int 转换为枚举?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11452920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast int to enum in C++?
提问by user1509260
How do I cast an int to an enum in C++?
如何在 C++ 中将 int 转换为 enum?
For example:
例如:
enum Test
{
A, B
};
int a = 1;
How do I convert a
to type Test::A
?
我如何转换a
为类型Test::A
?
回答by Andrew
int i = 1;
Test val = static_cast<Test>(i);
回答by bames53
Test e = static_cast<Test>(1);
回答by user1515687
Your code
你的代码
enum Test
{
A, B
}
int a = 1;
Solution
解决方案
Test castEnum = static_cast<Test>(a);
回答by Tommy
Spinning off the closing question, "how do I convert a to type Test::A
" rather than being rigid about the requirement to have a castin there, and answering several years late just this seems to be a popular question nobody else seems to have mentioned the alternative, per the C++11 standard:
剥离结束问题,“我如何将 a 转换为类型Test::A
”,而不是严格要求在那里进行演员表,并在几年后回答这似乎是一个受欢迎的问题,似乎没有其他人提到过替代方案, 根据 C++11 标准:
5.2.9 Static cast
... an expression
e
can be explicitly converted to a typeT
using astatic_cast
of the formstatic_cast<T>(e)
if the declarationT t(e);
is well-formed, for some invented temporary variablet
(8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.
5.2.9 静态转换
...如果声明格式正确,则 表达式
e
可以T
使用static_cast
形式的a 显式转换为类型,对于某些发明的临时变量(8.5)。这种显式转换的效果与执行声明和初始化,然后使用临时变量作为转换结果相同。static_cast<T>(e)
T t(e);
t
Therefore directly using the form t(e)
will also work, and you might prefer it for neatness:
因此,直接使用表单t(e)
也可以,您可能更喜欢它的整洁度:
auto result = Test(a);
回答by kosolapyj
Test castEnum = static_cast<Test>(a-1);
will cast a to A. If you don't want substruct 1, you can redefine enum
:
Test castEnum = static_cast<Test>(a-1);
将 a 转换为 A。如果您不想要 substruct 1,您可以重新定义enum
:
enum Test
{
A:1, B
};
In this case `Test castEnum = static_cast(a);' could be used to cast a to A.
在这种情况下`Test castEnum = static_cast(a);' 可用于将 a 强制转换为 A。