如果一个类将()运算符重载为成员函数,这个类就称为函数对象类,这个类的对象就是函数对象。函数对象是一个对象,但是使用的形式看起来像函数调用,实际上也执行了函数调用,因而得名。
函数对象的例子。
#include <iostream>
using namespace std;
class CAverage
{
public:
double operator()(int a1, int a2, int a3)
{
//重载()运算符
return (double)(a1 + a2 + a3) / 3;
}
};
int main()
{
CAverage average; //能够求三个整数平均数的函数对象
cout << average(3, 2, 3); //等价于 cout << average.operator(3, 2, 3);
return 0;
}
程序的输出结果是:
2. 66667
()是目数不限的运算符,因此重载为成员函数时,有多少个参数都可以。
average 是一个对象,average(3, 2, 3) 实际上就是 average.operator(3, 2, 3),这使得 average 看上去像函数的名字,故称其为函数对象。
函数对象在 accumulate 算法中的应用
STL 中有以下实现“累加”功能的算法(函数模板):
template <class InIt, class T, class Pred>
T accumulate(InIt first, InIt last, T val, Pred op);
该模板的功能是对 [first, last) 中的每个迭代器 I 执行 val = op(val, *I),返回最终的 val。在 Dev C++ 中,numeric 头文件中 accumulate 的源代码如下:
template <class InIt, class T, class Pred>
T accumulate(InIt first, Init last, T init, Pred op)
{
for (; first != last; ++first)
init = op(init, *first);
return init;
};
此模板被实例化后,op(init, *first)必须要有定义,则 op 只能是函数指针或者函数对象。因此调用该 accmulate 模板时,形参 op 对应的实参只能是函数名、函数指针或者函数对象。
下面的程序通过 accumulate 模板求一个 vector 中元素的平方和,其中用到了函数对象。
#include <iostream>
#include <vector>
#include <numeric> //accumulate 在此头文件定义
using namespace std;
template <class T>
void PrintInterval(T first, T last)
{
//输出区间[first,last)中的元素
for (; first != last; ++first)
cout << *first << " ";
cout << endl;
}
int SumSquares(int total, int value)
{
return total + value * value;
}
template<class T>
class SumPowers
{
private:
int power;