仿函数

<<C++标准程序库>>语录:

  “仿函数:行为类似函数的对象,这种对象叫做仿函数”

只需要在类成员中,增加一个重载括号运算符的函数。如下:

class X

{

  public:

    value operator() (arguments) const;

};

// 这样类X就能像函数一样被调用了... 也就是具有了函数行为...

// 在参数调用来临时,会产生一个临时对象op,并在函数体内调用op();

实例列举:

 1 #include <iostream>
 2 #include <list>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 class PrintInt
 7 {
 8 public:
 9     // Declaration of C++ call function. 
10     void operator()(int elem)const
11     {
12         cout << elem <<" ";
13     }
14 };
15 
16 void print(int elem)
17 {
18     cout << elem <<" "; 
19 }
20 int main()
21 {
22     list<int> li;
23     for(int i =1;i<=9;++i)
24         li.push_back(i);
25 
26     for_each(li.begin(),li.end(),PrintInt()); //调用仿函数
27     cout<<endl;
28 
29     for_each(li.begin(),li.end(),print);  // 调用函数
30     cout<<endl;
31 }

输出:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
请按任意键继续. . .

可以看出,两者具有同样的执行结果。。。

 

仿函数比起一般函数有以下优点:

1) 仿函数是智能函数

2) 每个仿函数都有自己的类型

3) 仿函数通常比一般函数速度快

 

 

posted on 2012-04-16 11:15  笔记吧... 可能只有自己看得懂  阅读(295)  评论(0编辑  收藏  举报