Question:
If I use the free functionoperator <
, 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; }
~~~ ^ ~~~
[/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
s.emplace(8);
s.emplace(-8);
for(auto t:s){ bool operator> (const my& other) const { If you have better answer, please add a comment about this, thank you!
cout<Answer:
They should be overloaded with const
directive. Otherwise, the non const operators can’t be applied to const my whatever
a.k.a. std::set<my>::key_type whatever
inside std::set
. Add
return this->a > other.a;
}
bool operator < (const my& other) const {
return this->a < other.a;
}
[/code]
other
should be passed by reference const my& other
.