函数对象:
使用具体的类对象取代函数
该类的对象具备函数调用的行为
构造函数指定具体数列项的起始位置
多个对象相互独立的求解数列项
先来看一个实现一个函数可以获得斐波那契数列每项的值
例子:
#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++)
{
cout << fib() << endl;
}
return 0;
}
结果:
sice@sice:~$ ./a.out
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
但是上面的例子存在缺陷,如果我们需要从头开始又得将a0,a1重新赋值0,1,显然存在弊端,而且无法指示从第N项开始返回,下面是进行改写的例子:
#include <iostream>
#include <string>
using namespace std;
class F
{
private:
int a0;
int a1;
public:
F(int n)
{
a0 = 0;
a1 = 1;
for(int i=2; i<=n; i++)
{
int t = a1;
a1 = a0 + a1;
a0 = t;
}
}
F()
{
a0 = 0;
a1 = 1;
}
int operator ()()
{
int ret = a1;
a1 = a0 + a1;
a0 = ret;
return ret;
}
};
int main()
{
F 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;
F fib2(10);
for(int i=0; i<5; i++)
{
cout << fib2() << endl;
}
return 0;
}
结果:
sice@sice:~$ g++ test.cpp
sice@sice:~$ ./a.out
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
55
89
144
233
377
可以看出我们使用重载操作符的概念实现了函数对象,使它可以从任意位置开始返回,还避免的全局变量的使用,可见函数对象是个多么强大的用法,函数调用操作()是可重载的,函数调用操作符只能通过类的成员函数重载(全局变量重载无效),还可以定义不同参数的多个重载函数,在工程中取代函数指针