繁体   English   中英

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

[英]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\9.2.0\include\c++\bits\char_traits.h:39,
                 from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ios:40,
                 from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ostream:38,
                 from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\iostream:39,
                 from 2.cpp:1:
c:\mingw\lib\gcc\mingw32\9.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\9.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++上编译,结果还是一样。

您在比较 function 时缺少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.";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM