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 for(int i=0;i<10;i++){ 31 //将类对象当做函数来使用,函数调用操作符() 32 cout << fib1() << endl; 33 } 34 for(int i=0;i<5;i++){ 35 cout << fib1() << endl; 36 } 37 38 Fib fib2; 39 for(int i=0;i<5;i++){ 40 cout << fib2() << endl; 41 } 42 43 Fib fib3(10); 44 for(int i=0;i<5;i++){ 45 cout << fib3() <<endl; 46 } 47 return 0; 48 }