首页 > 编程语言 > 详细

C++出现 error: no match for 'operator==' (operand types are 'Person' and 'const Person')

时间:2021-01-25 14:12:39      阅读:315      评论:0      收藏:0      [点我收藏+]

前提

用内置函数对象find测试查找自定义数据类型Person

代码

class Person{
public:
    string m_Name;
    int m_Age;
    Person(string name, int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }
};
void test01(void)
{
    vector<int> vec1;
    for(int i = 0; i < 10; i++)
    {
        vec1.push_back(i + 3);
    }
    //查找内置数据类型
    vector<int>::iterator pos1 = find(vec1.begin(), vec1.end(), 9);
    cout << *pos1 << endl;
    //查找自定义数据类型
    vector<Person> vec2;
    Person p1("aaa", 10);
    Person p2("bbb", 20);
    Person p3("ccc", 30);
    Person p4("ddd", 40);
    vec2.push_back(p1);
    vec2.push_back(p2);
    vec2.push_back(p3);
    vec2.push_back(p4);
    vector<Person>::iterator pos2 = find(vec2.begin(), vec2.end(), p1);
    cout << (*pos2).m_Name << " " << (*pos2).m_Age << endl;

}
int main(void)
{
    test01();
    system("pause");
    return 0;
}

错误

D:\software\destination\Qt5.6.1\Tools\mingw492_32\i686-w64-mingw32\include\c++\bits\predefined_ops.h:191: error: no match for ‘operator==‘ (operand types are ‘Person‘ and ‘const Person‘)
  { return *__it == _M_value; }
                 ^

 

分析

error: no match for ‘operator==‘没有匹配的==判断函数,说明编译器不知道Person类怎么比较算是两个对象相等

 

解决

在Person类中重载==运算符

class Person{
public:
    string m_Name;
    int m_Age;
    Person(string name, int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }
    bool operator ==(const Person& p)
    {
        return (this->m_Name == p.m_Name) && (this->m_Age == p.m_Age);
    }
};

 

C++出现 error: no match for 'operator==' (operand types are 'Person' and 'const Person')

原文:https://www.cnblogs.com/BASE64/p/14324533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!