函数对象(仿函数)
1 函数对象概念
概念:
- 重载函数调用操作符的类,其对象常称为函数对象
- 函数对象使用重载的()时,行为类似函数调用,也叫仿函数
本质:
函数对象(仿函数)是一个类,不是一个函数
2 函数对象使用
特点:
- 函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
- 函数对象超出普通函数的概念,函数对象可以有自己的状态
- 函数对象可以作为参数传递
#include<iostream>
using namespace std;
#include<string>
class MyAdd
{
public:
int operator()(int a, int b)
{
return a + b;
}
};//1、函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
void test01() {
MyAdd myadd;
int c= myadd(10, 20);
cout << c << endl;
}
//2、函数对象可以有自己的状态
class Myprint
{
public:
Myprint()
{
count = 0;
}
void operator()(string test)
{
cout << test << endl;
count++;
}
int count;
};
void test02() {
Myprint myprint;
myprint("hello c++");
myprint("hello c++");
myprint("hello c++");
myprint("hello c++");
cout << "myprint调用次数为:" << myprint.count << endl;
}
//3、函数对象可以作为参数传递
void doMyprint(Myprint &myy,string test)
{
myy(test);
}
void test03() {
Myprint mmm;
doMyprint(mmm, "开学啦啦啦啦");
}
int main()
{
test01();
cout << "--------------------------" << endl;
test02();
cout << "--------------------------" << endl;
test03();
system("pause");
return 0;
}
总结:
- 仿函数写法非常灵活,可以作为参数进行传递。
打个小广告,欢迎关注我的公众号“麦香E站”,分享人工智能,信通学习,数学提高,外语学习,生活理财等多方面知识以及我多年积累的学习资源分享~
公众号后台回复 “编程” 获取我多年来积攒的海量编程电子书~
后台回复“latex”获取我倾力所作latex快速入门手册~