您的位置:首页 > 财经 > 金融 > 网站设计远程培训_大连建设学校_江门搜狗网站推广优化_seo教育

网站设计远程培训_大连建设学校_江门搜狗网站推广优化_seo教育

2025/9/6 17:11:06 来源:https://blog.csdn.net/weixin_73266891/article/details/147288458  浏览:    关键词:网站设计远程培训_大连建设学校_江门搜狗网站推广优化_seo教育
网站设计远程培训_大连建设学校_江门搜狗网站推广优化_seo教育

仿函数(Functor)是 C++ 中一种行为类似函数的对象,它通过重载 operator() 来实现函数调用

1.基本仿函数

#include <iostream>
using namespace std;//定义仿函数
struct Add {int operator()(int a, int b) { return a + b; }
};int main()
{Add add; //创建仿函数对象cout << add(100, 101) << endl; //调用 add.operator()(100, 101)//输出:201return 0;
}
  • Add是一个仿函数,重载了 operator()

  • add(100, 101) 实际上调用 adder.operator()(100, 101)

2.仿函数可以存储状态(成员变量)

#include <iostream>
using namespace std;struct Mul {int factor;Mul(int f) :factor(f) {}int operator()(int x) { return x*factor; }
};int main()
{Mul m9(9);   //创建一个乘以 9 的仿函数Mul m10(10); //创建一个乘以 10 的仿函数cout << m9(2) << endl;  // 2 * 9  = 19cout << m10(2) << endl; // 2 * 10 = 20;return 0;
}
  • Mul存储了一个 factor(乘数)。

  • times9(2) 返回 9 * 2times10(2) 返回 10 * 2

3.对比普通函数

#include <iostream>
using namespace std;//普通函数
int add(int a, int b) {return a + b;
}// 仿函数
struct AddFunctor {int operator()(int a, int b) { return a + b; }
};int main() {//普通函数调用cout << add(2, 3) << endl;  // 5//函数调用AddFunctor adder;cout << adder(2, 3) << endl;  // 5return 0;
}
  • add(2, 3) 是普通函数调用。

  • adder(2, 3) 是仿函数调用,行为和普通函数一样。

4.仿函数用于 STL 算法

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;//仿函数:判断是否大于某个值
struct GreaterThan {int a;GreaterThan(int t) : a(t) {}bool operator()(int x) { return x > a; }
};int main() {vector<int> nums = {1, 5, 3, 7, 2, 8};//使用仿函数查找第一个大于 5 的数auto it = find_if(nums.begin(), nums.end(), GreaterThan(5));if (it != nums.end()) cout << "First number > 5: " << *it << endl;  // 7return 0;
}
  • GreaterThan(5) 构造了一个仿函数,用于判断数字是否大于 5

  • find_if 使用该仿函数查找符合条件的元素

5.仿函数作为回调

#include <string>
struct CallBack
{void operator()(const string &s) {cout << "CallBack: " << s << endl;}
};void func(const string &fs, CallBack cb) {cb("func: " + fs); //调用仿函数
}int main()
{CallBack cb;func("test", cb);//输出:CallBack: func: testreturn 0;
}
  • Callback 仿函数用于处理事件回调。

  • func调用仿函数 cb 并传递消息

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com