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

时间:2014-05-19 20:59:15

标签: c++ equality json-spirit custom-operator

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看起来像熟悉的&#34;左手边&#34;从许多其他例子中可以看出,如果分配给这个运算符的东西不在左侧,这将无法按预期工作。

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

在任何一种情况下,请引用标准。

1 个答案:

答案 0 :(得分:1)

b = x == y;会转换为b = x.operator==( y );,因此必须为operator==()定义x,其中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

}
相关问题