[英]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.如果我使用自由函数
operator <
,我的程序就可以工作。 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.它们应该用
const
指令重载。 Otherwise, the non const operators can't be applied to const my whatever
aka std::set<my>::key_type whatever
inside std::set
.否则,非 const 运算符不能应用于
const my whatever
aka std::set<my>::key_type whatever
里面的任何内容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
.另外
other
应该通过引用传递const my& other
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.