前提:
用内置函数对象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); } };