繁体   English   中英

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

[英]clang ++ build failed, but gcc build successfully

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM