函数调用运算符重载
函数调用运算符()也可以重载
由于重载后使用的方式非常像函数的调用,因此称为仿函数
仿函数没有固定写法,非常灵活 #include<iostream>
#include<string>
using namespace std;
//函数调用运算符重载
class MyPrint
{
public:
//重载函数调用运算符
void operator()(string text)
{ cout << text << endl;
} };
class MyAdd
{
public:
int operator()(int a, int b)
{ return a + b;
}
};
void test()
{
MyPrint myprint;
myprint("hello world");
MyAdd myadd;
cout << myadd(1, 2) << endl;
//匿名函数对象——特点:当前行被执行完立即释放
cout << MyAdd()(100,100) << endl;
}
int main(void)
{
test();
system("pause");
return 0;
}