简体   繁体   中英

Operator overloading enum class

I'm trying to overload the & operator of an enum class, but I'm getting this compiler error: error: no match for 'operator&=' (operand types are 'int' and 'Numbers'). Any ideas about this?

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

The compiler is telling exactly what's wrong. You didn't overload &= .

Despite the expected semantics, &= doesn't automatically expand to a = a & Numbers::one;

If you want to have both, the canonical way is to usually implement op in terms of op= . So your original function is adjusted as follows:

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

And the new one uses it:

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

Nice question but your tremendously helpful compiler diagnostic tells you everything you need to know.

You are missing the *bitwise AND assignment operator" : operator&= .

Yes you are overloading the operator & . But then you are using the operator &= which is a different one. Overload that too and you'll be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM