C++语法小记---函数对象

函数对象
  • 用于替代函数指针

  • 优势:函数对象内部可以保存状态,而不必使用全局变量或静态局部变量

  • 关键:重载"()"操作符

 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 ret = 0;
20 
21         ret = x;
22         x = y;
23         y = ret + x;
24         
25         return ret;
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 }

猜你喜欢

转载自www.cnblogs.com/chusiyong/p/11295105.html