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


    【1】复现问题

    为了更精确的分析,先用最简单的示例复现此错误场景,代码如下:

     1 #include <map>
     2 #include <string>
     3 
     4 struct Section
     5 {
     6     int id;
     7     std::string code;
     8 
     9     bool operator<(const Section& rhs)
    10     {
    11         return id < rhs.id;
    12     }
    13 };
    14 
    15 int main()
    16 {
    17     std::map<Section, std::string> stdMap;
    18     stdMap.insert(std::make_pair(Section{ 1 }, "kaizen1"));
    19     stdMap.insert(std::make_pair(Section{ 2 }, "kaizen2"));
    20     stdMap.insert(std::make_pair(Section{ 3 }, "kaizen3"));
    21 
    22     return 0;
    23 }

    编译结果:

    如上,稳定重现。

    【2】分析原因

    如上示例,你可能会问,明显已经实现了运算符<的重载,为什么还编译错误呢?

    注意仔细分析错误提示内容,从"const_Ty"字样不难看出编译器需要const支持。

    编译器限定,运算符“<”内部只需读取对象成员变量,体现出大小比较的原则即可,禁止对成员变量进行修改。

    所以,重载运算符“<”的实现必须要求const限定。

    【3】解决方案

    方案一:重载运算符“<”

    方案二:友元函数

    为了便于对比,两种方案代码放在一起,如下示例:

     1 #include <map>
     2 #include <string>
     3 
     4 struct Section
     5 {
     6     int id;
     7     std::string code;
     8 
     9 #if 1
    10     // 方案一:重载运算符<
    11     bool operator<(const Section & rhs) const   // 注意:第二个const
    12     {
    13         return id < rhs.id;
    14     }
    15 #else
    16     // 方案二:提供运算符<的友元函数
    17     friend bool operator<(Section const& lhs, Section const& rhs)
    18     {
    19         return lhs.id < rhs.id;
    20     }
    21 #endif
    22 };
    23 
    24 int main()
    25 {
    26     std::map<Section, std::string> stdMap;
    27     stdMap.insert(std::make_pair(Section{ 1 }, "kaizen1"));
    28     stdMap.insert(std::make_pair(Section{ 2 }, "kaizen2"));
    29     stdMap.insert(std::make_pair(Section{ 3 }, "kaizen3"));
    30 
    31     return 0;
    32 }

    方案一、第11行:两个const作用说明:

    (1)函数加上const后缀作用是限定函数内部实现对类成员变量具有只读权限。

    (2)形参类型加上const,限定在这个函数内部对用来进行比较的“原版对象”成员做任何修改。

    对于const的和非const的实参,函数都可以使用;如果不加,就只能接受非const的实参。

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

    备注:关于const关键字,建议参见随笔《const关键字

    方案二、参见随笔《友元》理解。

    【4】触类旁通

    如果是std::vector容器中存储自定义类型,又会有什么约束呢?

    详情参见随笔《ERROR:2676

    good good study, day day up.

    顺序 选择 循环 总结

  • 相关阅读:
    JS放在head和放在body中的区别
    模板模式(Template Pattern)
    原型模式
    Linux下的头文件搜索路径
    How to Change the Default Theme Appearance [editing with no theme]
    版本控制
    What is libacl.so.1 ?
    交叉编译器 arm-linux-gnueabi 和 arm-linux-gnueabihf 的区别
    mount --bind 的妙用
    mount的bind选项
  • 原文地址:https://www.cnblogs.com/Braveliu/p/14153482.html
Copyright © 2020-2023  润新知