BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #93094同步于 2016/8/22
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

调用操作符重载有什么用?

youmuyoumuyo
2016/8/22镜像同步10 回复
在公司看到了类似的代码 class A{ int operator()(int val){ cout<<val<<endl; } }; int main() { A a; int val=10; a(val); return 0; } 所以这里重载的意义是什么?和直接写一个正常的成员函数有区别吗?
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
chenxiansf机器人#1 · 2016/8/22
我想起了仿函数
Saerdna机器人#2 · 2016/8/22
省代码量
Aghanim机器人#3 · 2016/8/22
搬个板凳围观,感觉定义functor应该都有特定环境下的需求,这个例子太简单,没看出来意义。看暖神怎么说@nuanyangyang
aquamarine机器人#4 · 2016/8/22
可以把instance当函数用。
nuanyangyang机器人#5 · 2016/8/22
#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
youmuyoumuyo机器人#6 · 2016/8/22
我这段代码代表了公司代码的基本用法。。。 【 在 Aghanim 的大作中提到: 】 : 搬个板凳围观,感觉定义functor应该都有特定环境下的需求,这个例子太简单,没看出来意义。看暖神怎么说@nuanyangyang
youmuyoumuyo机器人#7 · 2016/8/22
暖神真厉害,网上查了好久都没查到 每次看到你的代码都开始怀疑自己。。。 【 在 nuanyangyang 的大作中提到: 】 : [code=c] : #include <algorithm> // sort : #include <iterator> // begin, end : ...................
ray19950624机器人#8 · 2016/8/24
暖神,请教一下。刚开始刷leetcode,请问一下程序runtime跟网速有关么?我知道这问题太low了....有时直接copy别人的算法,跑的也没他们声称的快,好疑惑啊。求赐教,灰常感谢。 【 在 nuanyangyang 的大作中提到: 】 : [code=c] : #include <algorithm> // sort : #include <iterator> // begin, end : ...................
nuanyangyang机器人#9 · 2016/8/24
想象力真丰富。 【 在 ray19950624 的大作中提到: 】 : 暖神,请教一下。刚开始刷leetcode,请问一下程序runtime跟网速有关么?我知道这问题太low了....有时直接copy别人的算法,跑的也没他们声称的快,好疑惑啊。求赐教,灰常感谢。