函数对象
函数对象的概念
1.重载函数调用操作符的类,其对象常称为函数对象;
2.函数对象使用重载的()时,行为类似函数调用,也叫仿函数
本质
函数对象仿函数是一个类,不是一个函数
函数对象使用
特点
1.函数对象在使用时,可以像普通函数那样去调用,可以有参数,可以有返回值
#include <iostream>
using namespace std;
class MyAdd
{
public:
int operator()(int v1, int v2) //参数
{
return v1 + v2; //返回值
}
};
void test1()
{
MyAdd myadd;
cout << myadd(10, 10) << endl;
}
int main()
{
test1();
system("pause");
return 0;
}
2.函数对象超出普通函数的概念,函数对象可以有自己的状态
#include <iostream>
using namespace std;
class MyAdd
{
public:
MyAdd()
{
this->Mycount = 0;
}
int operator()(int v1, int v2)
{
this->Mycount++;
return v1 + v2;
}
int Mycount; //定义一个变量记录状态
};
void test1()
{
MyAdd myadd;
cout << myadd(10, 10) << endl;
cout << myadd(10, 10) << endl;
cout << myadd(10, 10) << endl;
cout << myadd(10, 10) << endl;
cout << myadd(10, 10) << endl;
cout << myadd.Mycount << endl;
}
int main()
{
test1();
system("pause");
return 0;
}
3.函数对象可以作为参数传递
#include <iostream>
using namespace std;
class MyAdd
{
public:
MyAdd()
{
this->Mycount = 0;
}
int operator()(int v1, int v2)
{
this->Mycount++;
return v1 + v2;
}
int Mycount;
};
void doPrint(MyAdd& mp, int v1, int v2)
{
cout << mp(v1, v2) << endl;
}
void test1()
{
MyAdd myadd;
doPrint(myadd,10,11);
}
int main()
{
test1();
system("pause");
return 0;
}