#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int fib()
{
static int a0 = 0;
static int a1 = 1;
int ret = a1;
a1 = a0+a1;
a0 = ret;
return ret;
}
int main()
{
for(int i=0;i<10;i++)
{
cout<<fib()<<endl;
}
for(int i=0;i<5;i++)
{
cout<<fib()<<endl;
}
return 0;
}
输出结果:
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
解决方案
函数对象
使用具体的类对象取代函数
该类的对象具备函数调用的行为
构造函数指定具体数列项的起始位置
多个对象相互独立的求解数列项
函数对象
函数调用操作符
只能通过类的成员函数重载
可以定义不同参数的多个重载函数
#include <iostream>
#include <string>
using namespace std;
class Fib
{
int a0;
int a1;
public:
Fib()
{
a0 = 0;
a1 = 1;
}
Fib(int n)
{
a0 = 0;
a1 = 1;
for(int i=2; i<=n; i++)
{
int t = a1;
a1 = a0 + a1;
a0 = t;
}
}
int operator () ()
{
int ret = a1;
a1 = a0 + a1;
a0 = ret;
return ret;
}
};
int main()
{
Fib fib;
for(int i=0; i<10; i++)
{
cout << fib() << endl;
}
cout << endl;
for(int i=0; i<5; i++)
{
cout << fib() << endl;
}
cout << endl;
Fib fib2(10);
for(int i=0; i<5; i++)
{
cout << fib2() << endl;
}
return 0;
}
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
55
89
144
233
377