customer demand
-
Write a function
- Function to get the value of each term of Fibonacci series
- Return one value per call
- Functions can be reused as needed
Programming experiment: the first solution
#include <iostream> 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; }
Output: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
Existing problems
-
Once a function is called, it cannot be called again
- Static local variable is inside the function and cannot be changed outside
- Function is a global function. It is unique and cannot be used independently multiple times
- Cannot specify a specific sequence term as the initial value
Solution
-
Function object
- Replacing functions with concrete class objects
- Objects of this class have the behavior of function calls
- Constructor to specify the starting position of image items in a specific sequence
- Solving sequence terms independently for multiple objects
Function object
-
function call operator
- Can only be overloaded by a class's member function
- Multiple overloaded functions with different parameters can be defined
Programming experiment: the final solution
#include <iostream> using namespace std; class Fib { private: 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; }
Output: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 55 89 144 233 377
Summary
- Function call operator (()) is overloadable
- Function call operators can only be overloaded by class member functions
- Function call operators can define multiple overloaded functions with different parameters
- Function object is used to replace function pointer in Engineering
The above contents refer to the series courses of Ditai Software Institute, please protect the original!