c++ - 在 map 的类中定义运算符 < (c++)

标签 c++ dictionary

所以我有一个类:

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;
}

编译时报错:

"error passing 'const Time' as 'this' argument of std::string Time::see_day()" discards qualifiers[-fpermissive].

我想要这只是为了创建一个迭代器以按升序写入所有 map 。我做错了什么?

最佳答案

你需要标记你的

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

与行中的其他内容相同

return day < t1.see_day();

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

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

关于c++ - 在 map 的类中定义运算符 < (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418436/

相关文章:

c++ 函数——哪个日期是第一个/最后一个?

html - 如何添加图像映射链接?

c++ - 遍历标准映射并比较文本

swift - 使用 NSKeyedArchiver 保存一个不可编码的 Swift 字典

c++ - 使用指向 STL 映射的指针的操作

c++ - 模拟全局热键

c++ - fscanf 多行 [c++]

c++ - 用于将 std::string 转换为 QString 的包装器?

c++ - 为什么我的点没有在 OpenGL 中绘制鼠标所在的位置?

c# - 使用变量设置字典键和值类型