仿函数
- 介绍
- 仿函数使用
- 仿函数 重载函数调用运算符()
介绍
仿函数又称函数对象,是一种能够行使函数功能的类,该类重载了operator()运算符,调用仿函数的时候实际上就是通过类对象调用重载后的operator操作符,重载operator()和重载普通的函数效果相同,当参数类型不同时会执行不同的代码逻辑。
仿函数使用
复制代码
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#include <iostream> #include<typeinfo> using namespace std; class A { public: int operator ()(int a,int b) { return a+b; } double operator ()(double a,double b) { return (a+b)*2; } }; int main() { A ob; auto c1=ob(1,2); cout<<typeid(c1).name()<<" "<<c1<<endl; auto c2=ob(11.2,3.5); cout<<typeid(c2).name()<<" "<<c2<<endl; }
复制代码
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; using namespace std; class Fun { public: int my_add(int x,int y) { return x+y; } //重载() //第一个()是重载的符号 第二个()是标明要传参 int operator()(int x,int y) { return x+y; } }; int main() { Fun fun; cout<<fun.my_add(100,200)<<endl; cout<<fun.operator ()(100,200)<<endl; //优化 fun和()结合 就会自动寻找()运算符 cout<<fun(100,200)<<endl; //此处 fun(100,200)不是一个真正的函数 仅仅是一个对象名和()结合 调用()重载运 算符而已 //fun不是函数名 只是fun(100,200)类似一个函数调用 所以将fun(100,200)叫做 仿函数 //此处的Fun是类名称 //Fun()匿名对象 Fun()(100,200) 就是匿名对象(100,200) cout<<Fun()(100,200)<<endl;//了解 }
仿函数 重载函数调用运算符()
复制代码
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; class MyAdd { public: //本质就是成员函数 函数名叫operator() int operator()(int a, int b) { cout<<"调用了operator() int int"<<endl; return a+b; } int operator()(int a, int b, int c) { cout<<"调用了operator()int int int "<<endl; return a+b+c; } }; int main() { MyAdd ob1; cout<<ob1.operator ()(10,20)<<endl; //编译器优化 //严格意义:ob1是对象 和()结合 调用operator ()成员函数 //ob1(100,200) ob1本质是对象不是函数名 只是形式像函数调用 //叫做仿函数 cout<<ob1(100,200)<<endl; cout<<ob1(100,200,300)<<endl; cout<<MyAdd()(1000,2000)<<endl; }
最后
以上就是落后猫咪最近收集整理的关于c++仿函数介绍的全部内容,更多相关c++仿函数介绍内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复