运算符重载枚举类

JOK*_*JOK 3 c++ enums operator-overloading

我正在尝试重载&enum类的运算符,但是我得到了这个编译器错误:错误:'operator&='不匹配(操作数类型是'int'和'Numbers').有关于此的任何想法?

#include <iostream>
using namespace std;

enum class Numbers : int
{
    zero                    = 0, 
    one                     = 0x01,
    two                     = 0x02
};

inline int operator &(int a, Numbers b)
{
    return ((a) & static_cast<int>(b));
}

int main() {
    int a=1;
    a&=Numbers::one;
    cout << a ;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 5

编译器正确地告诉了什么是错的.你没有超负荷&=.

尽管有预期的语义,&=但不会自动扩展到a = a & Numbers::one;

如果你想兼得,规范的方法就是通常实现op的方面op=.所以您的原始功能调整如下:

inline int& operator &=(int& a, Numbers b)
{ // Note the pass by reference
    return (a &= static_cast<int>(b));
}
Run Code Online (Sandbox Code Playgroud)

新的使用它:

inline int operator &(int a, Numbers b)
{ // Note the pass by value
    return (a &= b);
}
Run Code Online (Sandbox Code Playgroud)