Overload problem <operator in C ++

I have a Student object vector that I want to sort using #include <algorithm>andsort(list.begin(), list.end());

To do this, I understand that I need to overload "<" but after trying (and failing) with several methods offered on the Internet, I run out of ideas.

Here is my last 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 that returns a string.

The program compiles and runs, but my operator function is never called during sorting, and when I tried to compare two Student objects, for example s1 < s2, I got an "error: overloaded statement not found"

How can I overload this statement correctly so that my view works as I assume?

+3
4

, , . ...

class Student
{
  public:
    bool operator< (const Student& second) const;
};

bool Student::operator< (const Student& second) const
{
  return (Name() < second.Name());
}

, , <, * .

EDIT , , . . . , .

+6

, , , , " ". friend ; , Student.h, . Student.cpp. ( .)

, - Student ( , () ). "friend" "extern", .

-, , . - , , , , ( - "this", - ), (, ).

+9

, this simple , :

class Student
{
    friend bool operator <(const Student& first, const Student& second)
    {
        return first.Name() < second.Name();
    }
    ...
};

"friend" - operator< . , Name() , .

+2

, :

class Student
{
    public:
    bool operator <(const Student& second) const;
    ...
    private:
    ...
};

With the implementation of comparing 'this' with the second. The question, in my opinion, is what did the “Name” method bring to the constellation? Because if it is not, you cannot write a const method that uses it.

+1
source

Source: https://habr.com/ru/post/1719849/


All Articles