函数调用运算符重载
函数调用运算符()也可以重载
由于重载后使用的方式非常像函数的调用,因此称为防函数
仿函数没有固定写法,非常灵活
函数调用运算符 () 可以被重载用于类的对象。当重载 () 时,您不是创造了一种新的调用函数的方式,相反地,这是创建一个可以传递任意数目参数的运算符函数。
如果类定义了调用运算符,则该类的对象称作函数对象
这篇文章比较详细C++重载运算:函数调用运算符
#include <iostream>
#include <string">
using namespace std;
//函数调用运算符重载
//打印输出类
class myPrint
{
public:
//重载函数调用运算符
void operator()(string test)
{
cout<<test<<endl;
}
};
class MyAdd
{
public:
int operator()(int v1,int v2){
return v1+v2;
}
};
void test01(){
myPrint mypint;
mypint("hello world");//由于使用起来非常像函数调用,因此称为仿函数
}
int main() {
test01();
cout<<MyAdd()(100,100)<<endl;
system("pause");
return 0;
}