代码之家  ›  专栏  ›  技术社区  ›  J. Doe

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

  •  3
  • J. Doe  · 技术社区  · 8 年前

    我有以下代码,我希望将其从朋友函数切换到成员函数:

    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 回复  |  直到 8 年前
        1
  •  4
  •   Sam Varshavchik    8 年前

    Both of your operators should be 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);
    }
    

    请注意,在 > 过载, right 是一个 const MyClass &

    因此 right.operator< 需要 < 操作员应为 常量 类方法,因为 正当 是警察。当你和一个 常量 对象,则只能调用其 常量 方法。不能调用其非- 常量 方法。