![](/img/trans.png)
[英]can we define 'operator<' as member function of a class to work with std::less?
[英]Why does std::set work with my free function operator<, but not my class member function operator<?
如果我使用自由函数operator <
,我的程序就可以工作。 如果我在类中使用实现,则会出现编译器错误。 为什么不将其作为类成员函数来实现?
我得到的部分错误:
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; }
~~~ ^ ~~~
编码 :
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<<",";
}
}
它们应该用const
指令重载。 否则,非 const 运算符不能应用于const my whatever
aka std::set<my>::key_type whatever
里面的任何内容std::set
。 添加
bool operator> (const my& other) const {
return this->a > other.a;
}
bool operator < (const my& other) const {
return this->a < other.a;
}
另外other
应该通过引用传递const my& other
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.