Reputation: 135
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;
}
Upvotes: 3
Views: 3088
Reputation: 170064
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);
}
Upvotes: 6
Reputation: 234665
Nice question but your tremendously helpful compiler diagnostic tells you everything you need to know.
You are missing the *bitwise AND assignment operator" : operator&=
.
Upvotes: 1
Reputation: 1663
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.
Upvotes: 0