Say I have a class where I overloaded the operator == as such:
Class A {
...
public:
bool operator== (const A &rhs) const;
...
};
...
bool A::operator== (const A &rhs) const {
..
return isEqual;
}
I already have the operator == return the proper Boolean value. Now I want to extend this to the simple opposite (!=). I would like to call the overloaded == operator and return the opposite, i.e. something of the nature
bool A::operator!= (const A &rhs) const {
return !( this == A );
}
Is this possible? I know this will not work, but it exemplifies what I would like to have. I would like to keep only one parameter for the call: rhs. Any help would be appreciated, because I could not come up with an answer after several search attempts.
You almost had it:
bool A::operator!= (const A &rhs) const {
return !( *this == rhs );
}
Note that this is a pointer, not the object. You need to dereference it. On a related note, it is usually better to implement most binary operators as free functions rather than member functions.
You don't have to do it on individual (per-class) basis.
The standard library already provides support for this approach, by declaring "default" template implementations for operators !=, >, <= and >=, which rely on user-provided operators == and <. These declarations are located in header <utility> and enclosed in namespace std::rel_ops.
Since these implementations are declared in namespace std::rel_ops, they are not found by default by name lookup. If you want to "activate" these definitions in your program, do
#include <utility>
using namespace std::rel_ops;
This, for example, will automatically derive operator != from your implementation of operator == for all classes in the translation unit. You can still override the mechanism by providing an explicit implementation of operator != for some specific class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With