简体   繁体   中英

Why does std::set work with my free function operator<, but not my class member function operator<?

If I use the free function operator < , my program works. If I use the implementation inside the class, I get a compiler error. Why doesn't implementing this as a class member function work?

Part of the error I get:

usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_function.h:386:20: error: invalid operands to binary expression ('const my' and 'const my')
      { return __x < __y; }
               ~~~ ^ ~~~

The code :

class my{

    public:
        int a;
        double b;
        my(int p){
            a=p;
            b=0;
        }
        bool operator> (const my other){
            return this->a > other.a;
        }
        bool operator < (const my other) {
            return this->a < other.a;
        }
};

//  bool operator < ( const my othe2,const my other) {
//             return othe2.a < other.a;
//         }

int main(){

    set<my> s={10,5};
    s.emplace(8);
    s.emplace(-8);

    for(auto t:s){
        cout<<t.a<<",";
    }

}

They should be overloaded with const directive. Otherwise, the non const operators can't be applied to const my whatever aka std::set<my>::key_type whatever inside std::set . Add

bool operator> (const my& other) const {
    return this->a > other.a;
}
bool operator < (const my& other) const {
    return this->a < other.a;
}

Additionally other should be passed by reference const my& other .

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