Search code examples
c++operator-overloadingmember-functionsfriend-function

C++ overloading: switching from friend to member function


I have this code which I wish to switch from friend functions to member functions:

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

I have got this far:

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

However, VC++ gives me this complain:

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

How can I fix this? Beside, is my operator> correctly written?


Solution

  • Both of your operators should be const class methods:

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

    Note that in the > overload, right is a const MyClass &.

    Therefore, right.operator< requires the < operator to be a const class method, because right is const. When you're playing games with a const object, you can only invoke its const methods. You cannot invoke its non-const methods.