返回信息流在公司看到了类似的代码
class A{
int operator()(int val){
cout<<val<<endl;
}
};
int main()
{
A a;
int val=10;
a(val);
return 0;
}
所以这里重载的意义是什么?和直接写一个正常的成员函数有区别吗?
这是一条镜像帖。来源:北邮人论坛 / cpp / #93094同步于 2016/8/22
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
调用操作符重载有什么用?
youmuyoumuyo
2016/8/22镜像同步10 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
#include <algorithm> // sort
#include <iterator> // begin, end
#include <cstdio>
using namespace std;
class IntComparator {
private:
bool backwards;
public:
IntComparator(bool _backwards): backwards(_backwards) {}
bool operator()(const int &a, const int &b) const {
if (backwards) {
return a > b;
} else {
return a < b;
}
}
};
int main() {
IntComparator asc(false), desc(true);
int ar1[] = {5,4,6,3,7,2,8,1,9};
int ar2[] = {5,4,6,3,7,2,8,1,9};
sort(begin(ar1), end(ar1), asc);
sort(begin(ar2), end(ar2), desc);
for (auto x : ar1) {
printf("%d ", x);
}
printf("\n");
for (auto x : ar2) {
printf("%d ", x);
}
printf("\n");
return 0;
}
结果:
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
我这段代码代表了公司代码的基本用法。。。
【 在 Aghanim 的大作中提到: 】
: 搬个板凳围观,感觉定义functor应该都有特定环境下的需求,这个例子太简单,没看出来意义。看暖神怎么说@nuanyangyang
暖神真厉害,网上查了好久都没查到
每次看到你的代码都开始怀疑自己。。。
【 在 nuanyangyang 的大作中提到: 】
: [code=c]
: #include <algorithm> // sort
: #include <iterator> // begin, end
: ...................
暖神,请教一下。刚开始刷leetcode,请问一下程序runtime跟网速有关么?我知道这问题太low了....有时直接copy别人的算法,跑的也没他们声称的快,好疑惑啊。求赐教,灰常感谢。
【 在 nuanyangyang 的大作中提到: 】
: [code=c]
: #include <algorithm> // sort
: #include <iterator> // begin, end
: ...................
想象力真丰富。
【 在 ray19950624 的大作中提到: 】
: 暖神,请教一下。刚开始刷leetcode,请问一下程序runtime跟网速有关么?我知道这问题太low了....有时直接copy别人的算法,跑的也没他们声称的快,好疑惑啊。求赐教,灰常感谢。