函数对象

  重载函数调用操作符的类,其对象称为函数对象(functio object),即它们是行为类似函数的对象,也叫仿函数(functor),其实就是重载“()”操作符,使得类对象可以像函数那样调用。

注意:

1、函数对象(仿函数)是一个类的实例化对象,不是一个函数。

2、函数对象(仿函数)重载了”() ”操作符使得它可以像函数一样调用。

作用:

1、函数对象超出了普通函数的概念,可以保存函数的调用状态。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 //函数对象超出了普通函数的概念,可以保存函数的调用状态
 5 class MyPrint
 6 {
 7 public:
 8     MyPrint() : printCount(0){}
 9     void operator()(int val)
10     {
11         printCount++;
12         cout << val << endl;
13     }
14 public:
15     int printCount;
16 };
17 
18 void test()
19 {
20     MyPrint print;//函数对象
21     for (int i = 0; i < 5; ++i)
22         print(i);
23     cout << "打印次数:" << print.printCount << endl;
24 }
25 
26 int main(void)
27 {
28     test();
29     return 0;
30 }
View Code

2、函数对象有类型的概念,可以做参数和返回值。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 //函数对象可以做参数和返回值
 5 class MyPrint
 6 {
 7 public:
 8     MyPrint() : printCount(0){}
 9     void operator()(int val)
10     {
11         printCount++;
12         cout << val << endl;
13     }
14 public:
15     int printCount;
16 };
17 
18 void DoBusiness(MyPrint &print,int i)
19 {
20     print(i);
21 }
22 
23 void test()
24 {
25     MyPrint print;//函数对象
26     for (int i = 0; i < 5; ++i)
27         DoBusiness(print, i);//把函数对象当做实参
28     cout << "打印次数:" << print.printCount << endl;
29 }
30 
31 int main(void)
32 {
33     test();
34     return 0;
35 }
View Code

3、在C++STL算法中,需要传入函数对象。

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <functional>
 5 using namespace std;
 6 
 7 void test(void)
 8 {
 9     vector<int> v;
10     v.push_back(10);
11     v.push_back(70);
12     v.push_back(50);
13     v.push_back(20);
14 
15     //sort默认按照从小到大排序
16     sort(v.begin(), v.end());
17     for_each(v.begin(), v.end(), [](int val)->void{cout << val << " "; });
18     cout << endl;
19     //greater<int>(),为一个匿名的函数对象,让sort按照从大到小排序
20     sort(v.begin(), v.end(), greater<int>());
21     for_each(v.begin(), v.end(), [](int val)->void{cout << val << " "; });
22     cout << endl;
23 }
24 
25 int main(void)
26 {
27     test();
28     return 0;
29 }
View Code
原文地址:https://www.cnblogs.com/yongqiang/p/5748195.html