ERROR:C2678 二进制“<”: 没有找到接受“const _Ty”类型的左操作数的运算符(或没有可接受的转换)

【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的实参。

另外补充,引用的作用避免在函数调用时对实参的一次拷贝,提高了效率。

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搁浅的渔

创作不易,多多支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值