Pau*_*ams 3 c++ operator-overloading
我有学生对象的载体,我想用排序#include <algorithm>和sort(list.begin(), list.end());
为了做到这一点,我理解我需要重载"<"运算符,但在尝试(并失败)使用在线建议的几种方法后,我的想法已经用完了.
这是我最近的尝试:
在Student.h ...
...
using namespace std;
class Student
{
friend bool operator <(const Student& first, const Student& second);
public:
...
private:
...
};
Run Code Online (Sandbox Code Playgroud)
在Student.cpp中......
...
#include "Student.h"
using namespace std;
...
bool operator <(const Student& first, const Student& second)
{
return first.Name() < second.Name();
}
Run Code Online (Sandbox Code Playgroud)
其中"Name()"是一个返回字符串的常量函数.
程序编译并运行,但我的操作符函数在排序期间从未被调用,当我尝试比较两个Student对象时,例如s1 < s2我收到了"错误:未找到重载的运算符"
我怎样才能正确地重载此运算符,以便我的排序可以按照我的意图运行?
您没有说明您使用的是哪种编译器,但我怀疑您使用的是最近实现"朋友不是声明"规则的编译器.类中的friend语句不作为函数声明; 包含Student.h的其他模块看不到该函数的任何声明.它只在Student.cpp文件中可见.(较旧的编译器没有此规则,并将朋友声明视为函数声明.)
该函数不需要是朋友,因为它不使用Student类的任何私有成员(我假设Name()是公共的).在类外移动函数声明,并将"friend"替换为"extern",它应该可以工作.
可以使操作员成为成员函数,如上面提到的一些海报,但是没有必要.使比较运算符成员函数通常不受欢迎,因为这意味着两个参数不是对称处理的(一个是不可见的"this"参数,另一个是正常的函数参数),在某些情况下会导致令人惊讶的结果(例如,可以对参数应用不同类型的转换).
我不会在这里使用朋友,我不确定它是否有效.我会用的是......
class Student
{
public:
bool operator< (const Student& second) const;
};
bool Student::operator< (const Student& second) const
{
return (Name() < second.Name());
}
Run Code Online (Sandbox Code Playgroud)
注意尾随const,表示在operator <,*中这是常量.
编辑我不能删除这个答案,因为它已被接受,但如果可以,我会.我也无法用正确的替换它.请参阅下面的Drew Dormanns评论,Ross Smiths回答.