重载操作符 - c++重载==操作符
PHPz
PHPz 2017-04-17 11:47:25
0
3
566
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; }

这样了?
正确的重载不同类型之间==操作符的作法是什么?

PHPz
PHPz

学习是最好的投资!

reply all(3)
左手右手慢动作

The correct approach is not to overload the == operator between different custom types. This does no good except confuse the person reading the code.

黄舟

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

in S
class S
{
    // ...
    bool operator ==(const S& s);
    // ...
};
刘奇

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template