函数对象

来源:互联网 发布:ps mac 编辑:程序博客网 时间:2024/05/11 20:07

让对象表现的和函数一样,这种技术在STL的算法库中满是遍布。《STL源码剖析》将函数对象翻译为”仿函数“。

函数对象是这样的类的对象,这个类重载了函数调用运算符,即( )运算符。假设类Test有对象test,那么test(10)类的调用就类似函数调用,把这种情况称为函数对象。

下列是一个示例代码:

#include <iostream>#include <algorithm>using namespace std;class Test{public:Test(const int x = 0):value(x){}int operator() (int x){return (value > x) ? value : x;}private:int value;};int compare(int x){return (10 > x) ? 10 : x;}void main(){Test test;cout << test(9) << endl;//用非匿名函数对象int array[10];int arrLength = sizeof(array)/sizeof(array[0]);int index = 0;for(; index < arrLength; index++){array[index] = index;}index = 0;for( ; index < arrLength; index++){cout <<  *find_if(array, array + arrLength -1, Test(index));//匿名函数对象//Test(index)是手动调用构造函数,此处会生成一个临时对象,然后这个临时对象在find_if函数中调用()操作符//如果没有重载函数调用运算符,则会出现编译错误cout <<  *find_if(array, array + arrLength -1, compare);}cout << endl;}



原创粉丝点击