Small note --- C ++ syntax function object

Function object
  • Alternatively a function pointer

  • Advantages: internal function object can save the state, instead of using a global variable or static local variable

  • Key: Overload "()" operator

 

 1 #include<iostream>
 2 #include<string>
 3 
 4 using namespace std;
 5 /* 计算Fib数列 */
 6 class Func
 7 {
 8     int x;
 9     int y;
10 public:
11     Func(int x = 1, int y = 1)
12     {
13         this->x = x;
14         this->y = y;        
15     }
16      
17      int operator () ()
 18      {
 19          int K = 0 ;
20  
21          K = x;
22          x = y;
23          y = K + X;
24          
25          return the right;
26      }
 27  };
28  
29  int main ()
 30  {
 31      Func f1;
32      for ( int i = 0 ; i < 10 ; i ++ )
 33      {
 34         cout << f1 () << endl;
35      }
 36      return  0 ;
37 }

 

Guess you like

Origin www.cnblogs.com/chusiyong/p/11295105.html