C++深度解析 函数对象分析 --- 重载函数调用操作符()(34)
客户需求:
编写一个函数
- 函数可以获得斐波那契数列每项的值
- 每调用一次返回一个值(1 1 2 3 5 8 13)
- 函数可根据需要重复使用
第一次调用返回1,第二次调用返回1,第三次调用返回2,第四次调用返回3,第五次调用返回5,第六次调用返回8,第七次调用返回13。
示例程序:
#include <iostream>
#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;
}
cout << endl;
for(int i = 0; i < 5; i++)