Reputation: 13
I'm learning C + +. The following is a simple demo. I can compile successfully with gcc-10.2 on MacOS, but clang-12.0 fails
class Person{
public:
string name;
int sex;
int age;
Person(string name, int sex, int age){
this -> name = name;
this -> sex = sex;
this -> age = age;
}
public:
bool operator==(const Person &person)
if ((name == person.name) && (sex==person.sex) && (age=person.age)){
return true;
}else{
return false;
}
}
};
int main()
{
vector<Person> v;
v.push_back(Person("tom",1,20));
v.push_back(Person("tom",1,20));
v.push_back(Person("jessei",0,21));
vector<Person>::iterator it = adjacent_find(v.begin(),v.end());
cout << it->name<<":" << it->age<<":" << it-> sex << endl;
return 0;
}
Here is the error log:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:678:71: error: invalid operands to binary expression
('const Person' and 'const Person')
bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
Upvotes: 1
Views: 276
Reputation: 3984
There are several errors in the source code, but I think it's better to let you discover and correct them yourself.
Back to your question, you missed a const after operator==.
bool operator==(const Person &person) const {
return xxx;
}
A better one would probably add constexpr and noexcept too (for modern c++).
constexpr bool operator==(const Person &person) const noexcept {
return xxx;
}
Upvotes: 2