函数对象概念:重载函数调用操作符的类,其对象称为函数对象
函数对象使用重载()时,行为类似函数调用,也叫仿函数
函数对象(仿函数)本质是一个类,不是一个函数
class myadd
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
//1函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
void test01()
{
myadd a;
cout << a(10, 20) << endl;
}
//函数对象超出普通函数的概念,函数对象可以有自己的状态
class myprint
{
public:
myprint()
{
this->count = 0;
}
void operator()(string test)
{
cout << test<<endl;
this->count++;
}
int count; // 内部自己状态
};
void test02()
{
myprint m;
m("hello");
cout << m.count << endl;
}
//函数对象可以作为参数传递
void doprint(myprint &m , string test)
{
m(test);
}
void test03()
{
myprint m1;
doprint(m1, "hello");
}
int main()
{
test01();
test03();
system("pause");
return 0;
}