自定义==运算符,哪一边重要吗?

custom == operator, does it matter which side?

本文关键字:运算符 自定义      更新时间:2023-10-16

JSON Spirit有一个方便operator==

template< class Config >
bool Value_impl< Config >::operator==( const Value_impl& lhs ) const
{
    if( this == &lhs ) return true;
    if( type() != lhs.type() ) return false;
    return v_ == lhs.v_; 
}

变量lhs看起来像许多其他示例中熟悉的"左侧",这意味着如果为该运算符分配的内容不在左侧,这将无法按预期工作。

这是对的吗? 如果是这样,为什么?

无论哪种情况,请引用标准。

b = x == y;翻译为b = x.operator==( y );因此必须为x定义一个operator==(),该它接受任何类型的参数y

class Y
{
    public:
};
class X
{
    public:
    bool operator==( Y rhs )
    {
        return false;
    }
};
void tester()
{
    X x;
    Y y;
    bool b = x == y; // works
    b = y == x;      // error
}