gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:09:20 26 4
gpt4 key购买 nike

所以我有一个类:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com