仿函数(functor),是通过重载()运算符模拟函数形为的类。
因此,这里需要明确两点:
1 仿函数不是函数,它是个类;
2 仿函数重载了()运算符,使得它可以像函数那样子调用(代码的形式好像是在调用函数)。
特性:
- 在类中进行,重载运算符()的函数;
- 重载后的函数称为仿函数
- 仿函数没有固定写法,非常灵活
代码:
#include <iostream>
using namespace std;
//仿函数
//打印操作
class Myprint
{
public:
void operator()(string test)
{
cout << test << endl;
}
};
//仿函数非常灵活,没有固定的写法
//加法类
class Add
{
public:
int operator()(int num1,int num2)
{
return num1 + num2;
}
};
//普通函数操作
void Myprint2(string test)
{
cout << test << endl;
}
void test01()
{
Myprint my;
my("Hello World"); //重载函数调用运算符()后的写法,和普通函数非常类似,因此成为仿函数
Myprint2("Hello World"); //普通函数调用
}
void test02()
{
Add add;
//add.operator()(10, 10); 本质写法
add(10, 10); //等同于add.operator()(10, 10) 简化了写法
cout << add(10, 10);
cout << endl;
//匿名函数对象 //Add是类的名字,后面跟一个括号是它的匿名对象,然后匿名对象重载(),因此是匿名函数对象
Add()(20, 20); // 就是如果我不想去创建一个对象,可以用匿名对象 创建方式 类名()(参数);
cout<< Add()(20, 20);
}
int main()
{
test01();
test02();
return 0;
}