3

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

3 Answers 3

6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.