前提:
用内置函数对象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);
}
};
原文链接: https://www.cnblogs.com/BASE64/p/14324533.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/207657
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!