我有学生对象的载体,我想用#include <algorithm>
和sort(list.begin(), list.end());
问题重载<运算符在C++
为了做到这一点进行排序,我明白,我需要超负荷“<”操作,但后尝试(和失败)在网上建议的几种方法,我没有想法。
这里是我的最新尝试:
在Student.h ...
...
using namespace std;
class Student
{
friend bool operator <(const Student& first, const Student& second);
public:
...
private:
...
};
而且在Student.cpp ...
...
#include "Student.h"
using namespace std;
...
bool operator <(const Student& first, const Student& second)
{
return first.Name() < second.Name();
}
其中 “名称()” 是一个返回字符串的常量函数。
程序编译和运行,但我的操作功能排序过程中,不会被调用,当我试图比较两个Student对象像s1 < s2
我得到了一个:
我该如何正确过载“错误没有发现超载运营商”这个操作符,这样我的排序将按我的意图工作?
我想我终于决定把它作为我会选择的答案,因为这是最直接导致我发现我的指针遇到的更大问题的答案。 –
这种方法经常被避免,因为如果类型可转换为学生,代码将转换右侧类型,但不转换左侧类型。朋友功能对于双方来说都是一致的。 –