gpt4 book ai didi

c++ - clang++构建失败,但gcc构建成功

转载 作者:行者123 更新时间:2023-12-03 07:15:30 25 4
gpt4 key购买 nike

我正在学习C++。以下是一个简单的演示。我可以在MacOS上使用gcc-10.2成功编译,但是clang-12.0失败

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;
}
这是错误日志:
/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;}

最佳答案

源代码中有几个错误,但是我认为最好自己发现并更正它们。
回到您的问题,您在operator ==之后错过了一个const。

bool operator==(const Person &person) const {
return xxx;
}
更好的一个可能会添加constexpr和noexcept(对于现代c++)。
constexpr bool operator==(const Person &person) const noexcept {
return xxx;
}

关于c++ - clang++构建失败,但gcc构建成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64587110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com