枚举类 "could not convert to unsigned int"

Enum Class "could not convert to unsigned int"

本文关键字:to unsigned convert int not could 枚举      更新时间:2023-10-16

我有一个类似这样的枚举类:

    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;
}