简体   繁体   中英

clang ++ build failed, but gcc build successfully

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;}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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