如何将一个枚举值转换为另一个枚举 [英] How to cast / assign one enum value to another enum

查看:497
本文介绍了如何将一个枚举值转换为另一个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的模块有两个枚举,它们具有完全相同的值集。如何投递给另一个人?

  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 enums are really just integers. Anyway, IMHO it is good practice to make an explicite cast.

这篇关于如何将一个枚举值转换为另一个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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