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

标签 c++ clang

我正在学习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/

相关文章:

c++ - 该对象具有与覆盖 draw 的成员函数 sfml 不兼容的类型限定符

c++ - 不用 goto 重构代码

c++ - 在 Linux 中测量 C++ 系统调用命令的时间

c++ - clang++ 3.2 链接器找不到 C++ stdlib

c++ - 警告: "when type is in parentheses, array cannot have dynamic size"?的原因是什么

c++ - 为什么 cin.clear() 会修复由 cin 错误输入引起的无限循环?

c++ - 具有模板模板参数的CRTP派生类

c++ - 即时编译 C++ : clang/libtooling fails to set Triple for LLVM IR

clang - 如何使用 libfuzzers 自定义修改器 API?

ubuntu - C 编译器无法在使用 LLVM 构建 Coreutils 期间创建可执行文件