简体   繁体   English

如何使用 C++ 将 const 枚举变量分配给普通枚举变量?

[英]How to assign const enum variable to normal enum variable using C++?

I have two enum's like as shown below:我有两个枚举,如下所示:

typedef enum {
    NONE = 0,
    test1,
    test2
} TestType;

enum class type
{
    zero = 0,
    one,
    two,
    three
};

When I am assigning one enum to another like as shown below:当我将一个枚举分配给另一个枚举时,如下所示:

const type f_eType;
TestType l_etestType = f_eType;

I am getting the below error:我收到以下错误:

a value of type "type" cannot be used to initialize an entity of type "TestType" “type”类型的值不能用于初始化“TestType”类型的实体

Could someone please help me how to resolve this error without using static_cast .有人可以帮助我如何在不使用static_cast的情况下解决此错误。

If you don't want to use static_cast then you'll have to define the conversion behaviour on your own:如果您不想使用static_cast那么您必须自己定义转换行为:

TestType convert(type val) {
   switch(val) {
   case type::zero:
       return NONE;
   //...
   }
}
TestType l_etestType = static_cast<TestType>(f_eType)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM