I understand C++ can't define operator==
automatically for a class, but why can't it use !(a == b)
for a != b
when operator!=
isn't available but operator==
is?
I'm aware of std::rel_ops
although I hadn't heard of it before today.
You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions.
Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof , which is technically an operator).
Operator overloading facilitates the specification of user-defined implementation for operations wherein one or both operands are of user-defined class or structure type. This helps user-defined types to behave much like the fundamental primitive data types.
It's not possible to overload the ternary operator.
Because operator==
does not necessarily mean the opposite of operator!=
.
I cannot think of any instance where operator==
would not mean !operator!=
, but they are separate operators. One of the most liberating and, at times, most frustrating things about C++ is that C++ applies a minimal set of restrictions about how you can write your code. If you have an instance where operator==
is not the opposite of operator!=
, then you should be able to express that in C++. And, in fact, you can.
You take the good with the bad in C++. You may consider this to be in the set of "the bad".
Bear in mind that in the vast majority of cases, it is trivial to correctly implement operator!=
in terms of operator==
.
bool Gizmo::operator!=(const Gizmo& rhs) const
{
return !operator==(rhs);
}
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