正确的重载方式<运营商?

时间:2012-10-26 02:52:09

标签: c++ operator-overloading

我有一个名为user的类,它有一个lname字段。这是重载“<”的正确方法吗?操作

bool User::operator<(const User& other)
{
    std::cout << "< operator was called" << std::endl;
    if (this != &other)
    {
        if (lname.compare(other.lname) == 0)
        {
            return true;
        }
    }
    return false;
}

我试图在一组更复杂的事情中使用它并且它失败了 - 只是想确保这一点是正确的。

4 个答案:

答案 0 :(得分:3)

正如其他人所指出的那样,您的operator<不允许左侧为const。将功能签名更改为

bool User::operator<(const User& other) const

是一项改进。但我实际上建议把它变成非会员功能:

class User {
public:
    friend bool operator<(const User& u1, const User& u2);
    // ...
};

bool operator<(const User& u1, const User& u2)
{
    // ...
}

首先,我认为它更清晰。

但是,它有时会产生技术差异。使用非成员函数时,表达式a < b会尝试对ab进行隐式转换,以查看您的operator<是否是可行的重载。但是使用成员函数,隐式转换可以应用于b,但不适用于aa必须是User类型或派生类型。这可能导致令人惊讶的情况,a < b编译但b < a没有编译。

答案 1 :(得分:2)

将“名称”字段隐藏为私有似乎更好。

return lname.compare(other.getName()) < 0;

答案 2 :(得分:1)

尝试:

bool User::operator<(const User& other) const
{
    return lname.compare(other.lname) < 0;
}

答案 3 :(得分:1)

实现operator<的正确方法是作为const函数:

bool User::operator<( const User& other ) const

这意味着该函数不会修改其成员,因此可以在类的const实例上调用。