如何将一个枚举值转换为另一个枚举 [英] How to cast / assign one enum value to another enum
问题描述
typedef EnumA {
a_dog = 0,
a_cat = 1
}枚举;
typedef EnumB {
b_dog = 0,
b_cat = 1
}枚举B;
枚举a = a_dog;
EnumB b;
b = a;
这样的作业会导致一个警告:枚举类型与另一个类型混合
我可以通过类型转换避免switch-case,例如
b =(int)a;
或
b =(EnumB)a;
我从您的问题中创建了一个工作代码。您已经错过了您的类型定义中的枚举
。
typedef枚举EnumA
{
a_dog = 0,
a_cat = 1
}枚举;
typedef枚举EnumB
{
b_dog = 0,
b_cat = 1
}枚举B;
int main()
{
EnumA a = a_dog;
EnumB b;
b =(EnumB)a;
printf(%d\\\
,b);
return 0;
}
代码 b = a
也可以正常工作,没有演员。另外 b =(int)a;
正在工作 - 至少在C11中,因为枚举
只是整数。无论如何,嗯,这是一个很好的做法做一个明确的演员。
I have 2 enums in 2 different modules that have exactly same value-set. How can I cast one to another?
typedef EnumA{
a_dog = 0,
a_cat = 1
} EnumA;
typedef EnumB{
b_dog = 0,
b_cat = 1
} EnumB;
EnumA a = a_dog;
EnumB b;
b = a;
Such an assignment is resulting in a warning: enumerated type mixed with another type Can I avoid switch-case by typecasting, like say
b = (int)a;
or
b = (EnumB)a;
I made a working code from your question. You have missed the enum
from your type definitions.
typedef enum EnumA
{
a_dog = 0,
a_cat = 1
} EnumA;
typedef enum EnumB
{
b_dog = 0,
b_cat = 1
} EnumB;
int main()
{
EnumA a = a_dog;
EnumB b;
b = (EnumB) a;
printf("%d\n", b);
return 0;
}
The code b = a
also works properly without the cast. Also b = (int) a;
is working - at least in C11, becuse enum
s are really just integers. Anyway, IMHO it is good practice to make an explicite cast.
这篇关于如何将一个枚举值转换为另一个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!