Home  >  Q&A  >  body text

重载操作符 - c++重载==操作符

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; }

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

PHPzPHPz2764 days ago539

reply all(3)I'll reply

  • ringa_lee

    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.

    reply
    0
  • 黄舟

    黄舟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

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

    reply
    0
  • 怪我咯

    怪我咯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.

    reply
    0
  • Cancelreply