枚举类 "could not convert to unsigned int"
Enum Class "could not convert to unsigned int"
我有一个类似这样的枚举类:
typedef unsigned int binary_instructions_t;
enum class BinaryInstructions : binary_instructions_t
{
END_INSTRUCTION = 0x0,
RESET,
SET_STEP_TIME,
SET_STOP_TIME,
START,
ADD
};
我正试图在开关语句中使用枚举的成员,如下所示:
const std::string& function(binary_instructions_t arg, bool& error_detect)
{
switch(arg)
{
case (unsigned int)BinaryInstructions::END_INSTRUCTION:
return "end";
break;
}
translate_error = true;
return "ERROR";
}
当基础类型已经是unsigned int
时,为什么需要转换为(unsigned int)
?
这是因为"enum class"是"强类型的",因此不能隐式转换为任何其他类型。http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations
因为C++11强类型枚举在设计上不能隐式转换为整型。底层类型是unsigned int
这一事实并不意味着枚举的类型为unsigned int
。它是BinaryInstructions
。
但实际上并不需要转换由于arg
是一个无符号int,因此需要强制转换,但为了清晰起见,您应该更喜欢static_cast
:
switch(arg)
{
case static_cast<unsigned int>(BinaryInstructions::END_INSTRUCTION) :
return "end";
break;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ Singleton - Prevent ::instance() to variable
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 如何解决"invalid conversion from 'char' to 'const char*'"
- "runtime error: addition of unsigned offset to 0x129000a0 overflowed to 0x12900088"
- memcpy unsigned char to int
- C++ cast char * to unsigned char
- CORBA IDL to C++ - char vs. unsigned char?
- 隐式转换更改符号性 'int " to 'unsigned int"
- 如何解决此棉绒警告"Implicit binary conversion from int to unsigned int"
- const char * to vector<unsigned char> Initalisation
- 错误消息"invalid conversion from ‘void*’ to ‘unsigned int’"
- Klocwork抱怨unsigned to zero的比较总是正确的——为什么?
- Unsigned int64 C++ to Java
- 枚举类 "could not convert to unsigned int"