仿函数:重载operator()的类

第一个仿函数的demo:

仿函数,就是实现了operator()重载的类。

“Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a regular function call, and therefore it can be used in templates instead of a pointer to a function.” —— www.cplusplus.com

#include<algorithm>
#include
<iostream>
#include
<vector>
using namespace std;
class CSum //仿函数类CSum
{
private:
int sum;
public:
CSum(){sum
=0;}
void operator()(int n){sum += n;}//重载了operator()运算符
    int getSum(){return sum;}
};

int main(int argc,char**argv)
{
vector
<int> v;
for(int i=0;i<100;++i)
v.push_back(i);
//我怀疑CSum()等同于两步,1是调用构造函数创建CSum对象并初始化sum,2是调用了100次重载函数operator()
    CSum obj = for_each(v.begin(),v.end(),CSum());
cout
<<obj.getSum()<<endl;
cin.
get();
return 0;
}

posted @ 2011-08-01 15:56  iliveido  Views(540)  Comments(2)    收藏  举报