【C++】35函数对象分析

【C++】35函数对象分析_第1张图片

#include 
#include 
#include 

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<

输出结果:

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610

解决方案

函数对象

使用具体的类对象取代函数

该类的对象具备函数调用的行为

构造函数指定具体数列项的起始位置

多个对象相互独立的求解数列项

函数对象

函数调用操作符

只能通过类的成员函数重载

可以定义不同参数的多个重载函数

#include 
#include 

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

小结:

函数调用操作符(())是可重载的

函数调用操作符只能通过类的成员函数重载

函数调用操作符可以定义不同参数的多个重载函数

函数对象用于在工程中取代函数指针

你可能感兴趣的:(c++)