zoukankan      html  css  js  c++  java
  • C++出现 error: no match for 'operator==' (operand types are 'Person' and 'const Person')

    前提

    用内置函数对象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:softwaredestinationQt5.6.1Toolsmingw492_32i686-w64-mingw32includec++itspredefined_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);
        }
    };
  • 相关阅读:
    JVM010JVM有哪些垃圾收集器
    MySQL005MySQL复制的原理是什么
    MySQL002MVCC解决的问题是什么
    MySQL007MySQL索引结构有哪些,各自的优劣是什么
    JVM011如何解决线上gc频繁的问题
    MySQL003MVCC实现原理是什么
    MySQL004MySQL的隔离级别有哪些
    MySQL006MySQL聚簇索引和非聚簇索引的区别
    MySQL001什么是MVCC
    MySQL008MySQL锁的类型有哪些
  • 原文地址:https://www.cnblogs.com/BASE64/p/14324533.html
Copyright © 2011-2022 走看看