ERROR:C2676 二进制“==”:“Student”不定义该运算符或到预定义运算符可接收的类型的转换

ERROR:C2676 二进制“==”:“Student”不定义该运算符或到预定义运算符可接收的类型的转换

多次被同事问到此类错误,于此备录一下。

【1】复现问题

用最简单代码复现说明此问题,示例如下:

 1 #include <iostream>
 2 #include <map>
 3 #include <string>
 4 #include <vector>
 5 
 6 struct Student
 7 {
 8     std::string code;  // 学号(唯一性标识)
 9     int grade;         // 年级
10     std::map<std::string, double> scores; // <科目,成绩>
11 };
12 
13 int main()
14 {
15     std::vector<Student> vecStu;
16     vecStu.push_back({ "080605109", 6, { {"English", 100}, {"China", 100} } });
17     vecStu.push_back({ "080605113", 7, { {"English", 96}, {"China", 67} } });
18     Student obj = { "080605114", 8, { {"English", 95}, {"China", 66} } };
19     vecStu.push_back(obj);
20     // 查找元素obj
21     {
22         auto iter = std::find(vecStu.begin(), vecStu.end(), obj);
23         if (iter != vecStu.end())
24         {
25             std::cout << "method3: find exists." << std::endl;
26         }
27     }
28 
29     return 0;
30 }

编译错误截图:

【2】原因分析

计算机弄不明白你想让它以什么标准来判断两个对象相等,所以你得给它确定了相等的标准或准则。

【3】解决方案

解决方案:自定义类,需要重载运算符“==”。

示例代码如下:

 1 #include <iostream>
 2 #include <map>
 3 #include <string>
 4 #include <vector>
 5 
 6 struct Student
 7 {
 8     std::string code;  // 学号(唯一性标识)
 9     int grade;         // 年级
10     std::map<std::string, double> scores; // <科目,成绩>
11 
12     bool operator==(const Student& obj) const
13     {
14         return obj.code == code; // 只要学号相同即可
15     }
16 };
17 
18 int main()
19 {
20     std::vector<Student> vecStu;
21     vecStu.push_back({ "080605109", 6, { {"English", 100}, {"China", 100} } });
22     vecStu.push_back({ "080605113", 7, { {"English", 96}, {"China", 67} } });
23     Student obj = { "080605114", 8, { {"English", 95}, {"China", 66} } };
24     vecStu.push_back(obj);
25     // 查找元素obj
26     {
27         auto iter = std::find(vecStu.begin(), vecStu.end(), obj);
28         if (iter != vecStu.end())
29         {
30             std::cout << "method3: find exists." << std::endl;
31         }
32     }
33 
34     return 0;
35 }

 

good good study, day day up.

顺序 选择 循环 总结

posted @ 2020-06-04 19:06  kaizenly  阅读(9124)  评论(0编辑  收藏  举报
打赏