1 #include<string> 2 using namespace std; 3 //重载函数调用操作符() 4 //函数对象取代函数指针 5 class Fib{ 6 private: 7 int a0; 8 int a1; 9 public: 10 Fib():a0(0),a1(1){ 11 //成员变量赋初值,初始化列表实现 12 } 13 Fib(int n):a0(0),a1(1){ 14 for(int i=2;i<n;i++){ 15 int ret = a1; 16 a1 = a0 + a1; 17 a0 = ret; 18 } 19 } 20 //函数对象实质还是操作符重载 21 int operator()(){ 22 int ret = a1; 23 a1=a0+a1; 24 a0=ret; 25 return ret; 26 } 27 }; 28 int main(){ 29 Fib fib1; 30 int main(){ 31 Fib fib1; 32 for(int i=0;i<10;i++){ 33 //将类对象当做函数来使用,函数调用操作符() 34 cout << fib1() << endl; 35 } 36 for(int i=0;i<5;i++){ 37 cout << fib1() << endl; 38 } 39 40 Fib fib2; 41 for(int i=0;i<5;i++){ 42 cout << fib2() << endl; 43 } 44 45 Fib fib3(10); 46 for(int i=0;i<5;i++){ 47 cout << fib3() <<endl; 48 } 49 return 0; 50 }