C++如何把数字转为枚举类型

一种方法使用swicth语句,
string getElemTypeName(ElemType type)
{
    switch(type)
    {
        case ElemType::CAP : return "CAP";break;
        case ElemType::IND : return "IND";break;
        case ElemType::VS :  return "VS";break;
        default: return "error"; break;    
    }
}
另一种方法,定义常量字符串数组,
const char* names[] = {"CAP","IND","VS"};
string getElemTypeName(ElemType type)
{
    int idx = static_cast<int>(type);
    return names[idx];
}

网上还有其他使用宏定义之类的方法,我觉得这两种方法够用就可以了。

猜你喜欢

转载自blog.csdn.net/qq_33485434/article/details/80533113