Here's the problem I'm having - I need to overload a class operator '==' so that I can compare multiple class variables in one evaluation. In my case, I need to compare 4 class variables. Here's what I've got:
Class declaration:
const bool& Class::operator == (const Class&);
Usage:
Class a, b, c, d;
if (a == b == c == d)
The compiler only allows me:
if ((a == b) && (a == c) && (a == d) && (b == c) && (b == d) && (c == d))
This seems really sloppy, and wouldn't be feasible to compare a large number of values. I can't declare multiple arguments for '==', such as:
works just fine! However, I am curious that the compiler suggested:
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'bool' (or there is no acceptable conversion)
could be 'bool std::operator ==(const std::_Exception_ptr &,const std::_Exception_ptr &)'
or 'bool std::operator ==(std::_Null_type,const std::_Exception_ptr &)'
or 'bool std::operator ==(const std::_Exception_ptr &,std::_Null_type)'
or 'bool std::operator ==(const std::error_code &,const std::error_condition &)'
or 'bool std::operator ==(const std::error_condition &,const std::error_code &)'
Why does it suggest multiple argument 'bool std::operator ==' operators?
constbool& Class::operator == (const Class&);
You return a reference to a local variable.
Do so: bool Class::operator == (const Class&) const;
And some notes:
1) Don't use notation const T& with basic integral types.
2) Always match const or/and valotatile specifiers to non-static member functions, when it's possibly.
Thanks for the tips, everyone! I have worked around this issue, but I will still continue to wonder. Standard types and constants can compare multiple variables just fine, as in:
1 2 3
int a, b, c, d;
if(a == b == c == d)
or: if(1 == 2 == 3 == 4)
The compiler even allows different types to be compared (with obvious warnings, of course):
1 2 3 4 5 6
char a;
int b;
float c;
double d;
if(a == b == c == d)
My solution was:
1 2 3
Class a, b, c, d;
if((a == b) && (b == c) && (c == d))