0

我有一个名为 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

4 回答 4

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,但不能应用于a:a必须是类型User或派生类型。a < b这可能导致编译但b < a不编译的令人惊讶的情况。

于 2012-10-26T03:04:54.733 回答
2

对我来说,将“lname”字段隐藏为私有似乎更好。

return lname.compare(other.getName()) < 0;
于 2012-10-26T03:07:02.847 回答
1

尝试:

bool User::operator<(const User& other) const
{
    return lname.compare(other.lname) < 0;
}
于 2012-10-26T02:56:27.840 回答
1

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

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

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

于 2012-10-26T02:57:22.643 回答