簡體   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