STL之函数对象
作者:互联网
摘要:本文主要介绍了函数对象(仿函数)的基本概念,并且举例子对其进行基本的使用。
1、基本概念
1.1 什么是函数对象?
重载函数调用操作符的类,其对象常称为函数对象(function object),即它们是行为类似函数的对象,也叫仿函数(functor),其实就是重载“()”操作符,使得类对象可以像函数那样调用。
1.2 注意
- 函数对象(仿函数)是一个类,不是一个函数。
- 函数对象(仿函数)重载了”() ”操作符使得它可以像函数一样调用。
1.3 分类
假定某个类有一个重载的operator(),而且重载的operator()要求获取一个参数,我们就将这个类称为“一元仿函数”(unary functor);相反,如果重载的operator()要求获取两个参数,就将这个类称为“二元仿函数”(binary functor)。
2、代码示例
1 #include<iostream> 2 3 using namespace std; 4 5 class Myprint { //定义重载函数调用操作符的类 6 public: 7 void operator() (int num){ //重载“()” 8 cout << "num " << num << endl; 9 count++; 10 } 11 int count = 0; 12 }; 13 14 void test01() { 15 Myprint myprint; //定义一个函数对象 16 myprint(100); //此时的对象就可以像函数一样调用,注意和有参构造函数相区别 17 myprint(100); 18 myprint(100); 19 cout << myprint.count << endl; //输出3,表明函数对象可以保存状态 20 21 //还可以使用匿名对象的方式来调用 22 Myprint()(1000); 23 } 24 25 //函数对象作为参数 26 void doprint(Myprint print,int num) { 27 print(num); 28 } 29 30 void test02() { 31 doprint(Myprint(), 10); //匿名调用方法 32 33 Myprint myprint; 34 doprint(myprint, 20); //非匿名调用 35 } 36 37 int main() { 38 //test01(); 39 test02(); 40 41 system("pause"); 42 return 0; 43 }
标签:函数,STL,functor,重载,对象,操作符,operator 来源: https://www.cnblogs.com/lzy820260594/p/11398661.html