Problem overloading the < operator in C++
c++, operator-overloading
Solution
I wouldn't use a friend here, and I'm not sure it works at all. What I would use is...
class Student
{
public:
bool operator< (const Student& second) const;
};
bool Student::operator< (const Student& second) const
{
return (Name() < second.Name());
}
Note the trailing const, indicating that within operator<, *this is constant.
EDIT I cannot delete this answer because it was accepted, but I would if I could. I also can't replace it with a correct one. See Drew Dormanns comment below, and Ross Smiths answer.
Problem
I have a vector of Student objects which I want to sort using `#include <algorithm>` and `sort(list.begin(), list.end());` In order to do this, I understand that I need to overload the "<" operator but after trying (and failing) with several methods suggested online, I am running out of ideas. Here is my latest attempt: In Student.h... ``` ... using namespace std; class Student { friend bool operator <(const Student& first, const Student& second); public: ... private: ... }; ``` And in Student.cpp... ``` ... #include "Student.h" using namespace std; ... bool operator <(const Student& first, const Student& second) { return first.Name() < second.Name(); } ``` where "Name()" is a constant function which returns a string. The program compiles and runs, but my operator function is never called during the sort and when I tried comparing two Student objects like `s1 < s2` I got an "error: overloaded operator not found" How can I correctly overload this operator so that my sort will work as I intend?