概念:
- 重载调用函数操作符的类,其对象称为函数对象
- 函数对象使用重载()时,行为类似函数调用,也叫仿函数
函数对象本质是一个类,不是一个函数
函数对象使用:
features:
1.函数对象在调用时,可以像普通函数一样调用,可以有参数,可以有返回值
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#include<iostream> using namespace std; #include<string> //函数对象 //1.函数对象在调用时,可以像普通函数一样调用,可以有参数,可以有返回值 class add { public: int operator()(int a,int b) { return a + b; } }; void test() { add ADD; cout << ADD(125, 125) << endl; } int main() { test(); system("pause"); return 0; }
2.函数对象超出普通函数的概念,函数对象可以有自己的概念
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30#include<iostream> using namespace std; #include<string> //函数对象 //2.函数对象超出普通函数的概念,函数对象可以有自己的概念 class add { public: void operator()(string txt) { cout << txt << endl; count++; } int count; }; void test() { add A; A.count = 0; A("函数对象"); A("函数对象"); A("函数对象"); cout << A.count << endl; } int main() { test(); system("pause"); return 0; }
3.函数对象可以作为参数传递
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31#include<iostream> using namespace std; #include<string> //函数对象 //3.函数对象可以作为参数传递 class add { public: void operator()(string txt) { cout << txt << endl; count++; } int count; }; void txt(add& A, string txt) { A(txt); } void test() { add A; A("函数对象做参数传递"); } int main() { test(); system("pause"); return 0; }
最后
以上就是精明海燕最近收集整理的关于函数对象--仿函数的全部内容,更多相关函数对象--仿函数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复