在映射的类中定义运算符< (c++)

Defining the operator < in a class for a map (c++)

本文关键字:lt c++ 运算符 映射 定义      更新时间:2023-10-16

我有一个class:

class Time{
    private:
    string day;
    string hour;
    public:
    //etc
    }

我在类中定义了:

bool Time::operator <(const Time &t1) const {
     if (day!= t1.see_day()) {
        return day < t1.see_day();
     }
     else return hour < t1.see_hour;
}

当我编译时,它给了我一个错误:

"将'const Time'作为std::string Time::see_day()的'this'参数传递错误"放弃限定符[-fpermissive].

我想用它来创建一个迭代器,以升序写所有的map。我做错了什么?

你需要标记你的

Time::see_day() const
//              ^^^^^
//             needs to be const

行相同
return day < t1.see_day();

试图在const实例(本例中为t1)上调用非const成员函数,这是被禁止的,因此出现错误。

Time::see_hour()相同的问题(您也有一个错字,缺少函数调用的括号)。