Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 超载的正确方法<;接线员?_C++_Operator Overloading - Fatal编程技术网

C++ 超载的正确方法<;接线员?

C++ 超载的正确方法<;接线员?,c++,operator-overloading,C++,Operator Overloading,我有一个名为user的类,它有一个lname字段。这是过载“的正确方法吗?请尝试: bool User::operator<(const User& other) const { return lname.compare(other.lname) < 0; } bool User::operator实现operator的正确方法正如其他人所指出的,您的operator我认为最好将“lname”字段隐藏为private return lname.compare(oth

我有一个名为user的类,它有一个lname字段。这是过载“的正确方法吗?请尝试:

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

bool User::operator实现
operator的正确方法正如其他人所指出的,您的
operator我认为最好将“lname”字段隐藏为private

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

第一个
返回false;
有点搞砸了。它还可能与
const
有关。
lname
是什么类型的?你不能只返回
lname.compare(other.lname)吗<0
或类似的东西?既然你没有指定
比较的内容,很难判断你做的是否正确。Bagh,对不起,返回false不是故意的。为什么对
操作符使用
==0
或者为什么你认为他的lname不是私有的?这个答案毫无意义,
用户::操作符
bool User::operator<( const User& other ) 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)
{
    // ...
}
return lname.compare(other.getName()) < 0;