基本概念:
我们将重载了小括号 ( ) 的类称为函数对象,也称为仿函数。因为它在使用小括号时,类似于调用函数的操作,所以称为仿函数。但是我们要知道,函数对象本质上还只是一个类,它并不是一个真正的函数。
仿函数的特点:
1.仿函数可以有自己的状态;
下面的类Func中我们可以利用count来记录类的调用次数,这就可以记录仿函数的状态;
2.仿函数可以作为函数参数传递;
下面的函数test01中调用test02,我们就可以将仿函数作为参数传递给test02,并且我们可以依此来在test02中调用之前的仿函数
3.仿函数有参数并且可以有返回值等函数的特性;
下图中我们正是利用这一点,在test01中设计了一个整型变量ret作为接收仿函数返回值的数据,并且我们在重载小括号运算符时也传递了参数。
class Func
{
public:
int operator()(int a,int b)
{
this->count++;
cout << a + b << endl;
return a - b;
}
int count=0;
};
void test02(Func& func)
{
func(9, 6);
func(3, 6);
cout << func.count << endl;
}
void test01()
{
Func func;
int ret=func(2, 3);
cout << ret<<endl;
test02(func);
}
int main()
{
test01();
return 0;
}
谓词
C++中的谓词,指定的是返回值为布尔类型的仿函数。
其中谓词又细分为一元谓词和二元谓词:
一元谓词就是接收的参数只有一个的仿函数;
二元谓词就是接收的参数有两个的仿函数;
一元谓词:
class Info
{
public:
bool operator()(int a)
{
return a;
}
};
int main()
{
Info in;
int num;
cin >> num;
if (!in(num))
{
cout << "is zero!" << endl;
}
return 0;
}
二元谓词:
这里使用二元谓词重新将sort函数的比较顺序写了一遍。注意,这里Compare( )是创建一个匿名对象,使用( )进行初始化;与我们在map容器中的不同,那里需要的是一个类型,这里需要的是一个类(仿函数)。
class Compare
{
public:
bool operator()(int a,int b)
{
return a > b;
}
};
void test()
{
vector<int> v;
v.push_back(2);
v.push_back(6);
v.push_back(9);
v.push_back(0);
v.push_back(1);
v.push_back(8);
sort(v.begin(), v.end(), Compare());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
cout << *it << " ";
}
int main()
{
test();
return 0;
}