【1】复现问题
为了更精确的分析,先用最简单的示例复现此错误场景,代码如下:
#include <map>
#include <string>
struct Section
{
int id;
std::string code;
bool operator<(const Section& rhs)
{
return id < rhs.id;
}
};
int main()
{
std::map<Section, std::string> stdMap;
stdMap.insert(std::make_pair(Section{ 1 }, "kaizen1"));
stdMap.insert(std::make_pair(Section{ 2 }, "kaizen2"));
stdMap.insert(std::make_pair(Section{ 3 }, "kaizen3"));
return 0;
}
编译结果:
如上,稳定重现。
【2】分析原因
如上示例,你可能会问,明显已经实现了运算符<的重载,为什么还编译错误呢?
注意仔细分析错误提示内容,从"const_Ty"字样不难看出编译器需要const支持。
编译器限定,运算符“<”内部只需读取对象成员变量,体现出大小比较的原则即可,禁止对成员变量进行修改。
所以,重载运算符“<”的实现必须要求const限定。
【3】解决方案
方案一:重载运算符“<”
方案二:友元函数
为了便于对比,两种方案代码放在一起,如下示例:
#include <map>
#include <string>
struct Section
{
int id;
std::string code;
#if 1
// 方案一:重载运算符<
bool operator<(const Section & rhs) const // 注意:第二个const
{
return id < rhs.id;
}
#else
// 方案二:提供运算符<的友元函数
friend bool operator<(Section const& lhs, Section const& rhs)
{
return lhs.id < rhs.id;
}
#endif
};
int main()
{
std::map<Section, std::string> stdMap;
stdMap.insert(std::make_pair(Section{ 1 }, "kaizen1"));
stdMap.insert(std::make_pair(Section{ 2 }, "kaizen2"));
stdMap.insert(std::make_pair(Section{ 3 }, "kaizen3"));
return 0;
}
方案一、第11行:两个const作用说明:
(1)函数加上const后缀作用是限定函数内部实现对类成员变量具有只读权限。
(2)形参类型加上const,限定在这个函数内部对用来进行比较的“原版对象”成员做任何修改。
对于const的和非const的实参,函数都可以使用;如果不加,就只能接受非const的实参。
另外补充,引用的作用避免在函数调用时对实参的一次拷贝,提高了效率。