C ++重载:从朋友切换到成员函数

时间:2018-04-17 03:07:32

标签: c++ operator-overloading member-functions friend-function

我有这个代码,我希望从友元函数切换到成员函数:

inline bool operator< (const MyClass& left, const MyClass& right)
{
    return (((left.value == 1) ? 14 : left.value) < ((right.value == 1) ? 14 : right.value));
}

inline bool operator> (const MyClass& left, const MyClass& right)
{
    // recycle <
    return  operator< (right, left);
}

我到目前为止:

inline bool MyClass::operator< (const MyClass& right)
{

    return (((this->value == 1) ? 14 : this->value) < ((right.value == 1) ? 14 : right.value));
}

inline bool MyClass::operator> (const MyClass& right)
{
    // recycle <
    return  right.operator<(*this);
}

然而,VC ++给了我这样的抱怨:

cannot convert 'this' pointer from 'const MyClass' to 'MyClass &'

我该如何解决这个问题?旁边,我的operator>是否写得正确?

1 个答案:

答案 0 :(得分:4)

您的两个运算符都应该是const类方法:

inline bool MyClass::operator< (const MyClass& right) const
{

    return (((this->value == 1) ? 14 : this->value) < ((right.value == 1) ? 14 : right.value));
}

inline bool MyClass::operator> (const MyClass& right) const
{
    // recycle <
    return  right.operator<(*this);
}

请注意,在>重载中,rightconst MyClass &

因此,right.operator<要求<运算符为const类方法,因为right是const。当您使用const对象玩游戏时,您只能调用其const方法。您无法调用其非const方法。