std::max 重载 less 运算符无法编译

std::max with overloaded less operator doesn't compile

代码如下:

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <utility>

struct student
{
    std::string full_name;
    int group;
    int number;

    friend std::istream& operator>>(std::istream& in, student& obj)
    {
        in >> obj.full_name >> obj.group >> obj.number;
        return in;
    }
    friend std::ostream& operator<<(std::ostream& out, const student& obj)
    {
        out << "Full name: " << obj.full_name << '\n';
        out << "Group: " << obj.group << '\n';
        out << "Number: " << obj.number << '\n';
        return out;
    }

    bool operator<(const student& obj)
    {
        return this->number < obj.number;
    }
};

int main()
{
    std::ifstream fin("input.txt"); 
    student a, b;
    fin >> a >> b;
    std::cout << std::max(a, b) << " studies at senior course.";
}

错误如下:

In file included from c:\mingw\lib\gcc\mingw32.2.0\include\c++\bits\char_traits.h:39,
                 from c:\mingw\lib\gcc\mingw32.2.0\include\c++\ios:40,
                 from c:\mingw\lib\gcc\mingw32.2.0\include\c++\ostream:38,
                 from c:\mingw\lib\gcc\mingw32.2.0\include\c++\iostream:39,
                 from 2.cpp:1:
c:\mingw\lib\gcc\mingw32.2.0\include\c++\bits\stl_algobase.h: In instantiation of 'constexpr const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = student]':
2.cpp:37:28:   required from here
c:\mingw\lib\gcc\mingw32.2.0\include\c++\bits\stl_algobase.h:227:15: error: no match for 'operator<' (operand types are 'const student' and 'const student')
  227 |       if (__a < __b)
      |           ~~~~^~~~~

有什么问题吗?我本可以使用 (a < b ? b : a) 而不是 std::max() 并且它会编译,但我仍然不明白第二个选项有什么问题。尝试在 visual studio 编译器和 g++ 上编译,结果仍然相同。

您缺少比较函数的 const 限定符:


#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>

struct student
{
    std::string full_name;
    int group;
    int number;

    friend std::istream& operator>>(std::istream& in, student& obj)
    {
        in >> obj.full_name >> obj.group >> obj.number;
        return in;
    }
    friend std::ostream& operator<<(std::ostream& out, const student& obj)
    {
        out << "Full name: " << obj.full_name << '\n';
        out << "Group: " << obj.group << '\n';
        out << "Number: " << obj.number << '\n';
        return out;
    }

    bool operator<(const student& obj) const { return this->number < obj.number; }
};

int main()
{
    std::ifstream fin("input.txt");
    student a, b;
    fin >> a >> b;
    std::cout << std::max(a, b) << " studies at senior course.";
}