bool operator==(const T& lhs, const T2& rhs);
像这样的重载似乎只对 (T)a==(T2)b
有效, 但是反过来(T2)b==(T)a
就不行了...
于是好像只有同时双向的进行重载:
bool operator==(const T& lhs, const T2& rhs);
bool operator==(const T2& lhs, const T& rhs) { return rhs == lhs; }
这样了?
正确的重载不同类型之间==操作符的作法是什么?
ringa_lee2017-04-17 11:49:25
The correct approach is not to overload the == operator between different custom types. This does no good except confuse the person reading the code.
黄舟2017-04-17 11:49:25
There are two places that may not be appropriate. One is overloading the == operator between different classes, which is against convention. The other is defined as a global method, destroying encapsulation.
Generally speaking, T and T2 should have a common parent class S, and overload the == operator
class S
{
// ...
bool operator ==(const S& s);
// ...
};
怪我咯2017-04-17 11:49:25
Since the types are different, what’s the point of comparison?
If you really want to compare, you should perform type conversion first.
Overloading the ==
operator has two ways to implement it. One is inside the class, and one parameter is enough; if it is implemented externally, use the two-parameter version.