函数调用运算符重载
- 函数调用运算符() 也可以重载
- 由于重载后使用的方式非常像函数的调用,因此称为仿函数
- 仿函数没有固定的写法,因此非常灵活
示例:
#include <iostream>
#include <string>
using namespace std;
class Persion
{
public:
// 重载的()操作符也称为仿函数
int operator()(int a,int b)
{
return a + b;
}
};
int main()
{
Persion p1;
int nNum = p1(3, 2);
cout << nNum << endl;
system("pause");
return 0;
}
小知识:
如果不想写对象,也可以创建一个匿名对象,如下:
class Persion
{
public:
int operator()(int a,int b)
{
return a + b;
}
};
// 匿名函数对象
cout << Persion()(1, 2) << endl;