c++(函数对象,也叫做仿函数)
c++(函数对象,也叫做仿函数)
基本使用
class MyPrint
{
public:
void operator()(int num)
{
cout << "num = " << num << endl;
cout++;
}
int count=0;
};
void test01()
{
//MyPrint是一个类,而不是函数
//第一种调用方式
MyPrint p;
p(11);
//第二种调用方式
MyPrint()(1000);
}
//函数对象超出了普通函数的概念,内部可以保存状态
void test02()
{
MyPrint p;
p(10);
p(10);
cout << p.count << endl;
}
//函数对象作为参数
void doPrint(MyPrint print, int num)
{
print(num);
}
void test03()
{
doPrint(MyPrint(), 10);
}
浙公网安备 33010602011771号