c++11的enum类型不能直接使用枚举标识符吗?

如下代码会报错:错误:no match for ‘operator&’ (operand types are ‘NameType’ and ‘int’)

必须强转为整形才行:if ((int)(NameType::Btype) & 1);但是感觉这样写起来很不优雅,能不能像类似非c++11的enum那样写:if (NameType::Btype & 1)。

enum class NameType : uint8_t {
    Atype = 0,
    Btype,
    Ctype
};

using namespace std;

int level = 100;
int sub(){
    printf("this is sub foo===%llu\n", NameType::Btype);
    if ((NameType::Btype) & 1) {  //报错:错误:no match for ‘operator&’ (operand types are ‘NameType’ and ‘int’)
        cout << 1 << endl;
    } else {
        cout << 0 << endl;
    }
    return 0;
}
阅读 1.9k
1 个回答
  • 不是优雅的问题,是在语法层面进行的“安全“与“灵活”的取舍
  • 用什么最好遵守它指定的规则,就像 C++ 中尽量使用引用而不是指针
  • C++ 中的类型转换 xxx_cast<>()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题