Lab 10 Function Pointer Allows your program to determine which - - PowerPoint PPT Presentation
Lab 10 Function Pointer Allows your program to determine which - - PowerPoint PPT Presentation
Lab 10 Function Pointer Allows your program to determine which function to call dynamically. - Example: double (*func) (double x); This function pointer signature is to take a double as parameter, and returns a double. typedef Allow you to
Allows your program to determine which function to call dynamically.
- Example:
double (*func) (double x); This function pointer signature is to take a double as parameter, and returns a double.
Function Pointer
typedef
Allow you to create alias for a data type, or a function. Example:
- typedef double Currency;
- typedef string FiveString[5];
- typedef double Func(double);
Function Pointer Example
Function Pointer Example
Function Pointer Example
Function Pointer Example
Function Pointer
//existing functions: int function1(){ ... } int function2(int x){ ... } int function3(int x,int y){ ... } int function4(int *x){ ... } //declaring a pointer to function: int (*f1)(); int (*f2)(int); Int (*f3)(int, int); int (*f4)(int *);
#include <iostream> using namespace std; typedef double (*FUNC)(double); double integrate(FUNC f, double a, double b) { // what goes here? } double line(double x){ return x; } double square(double x){ return x*x; } double cube(double x){ return x*x*x; } int main() { cout << "The integral of f(x)=x between 1 and 5 is: " << integrate(line, 1, 5) << endl; // 12 cout << "The integral of f(x)=x^2 between 1 and 5 is: " << integrate(square, 1, 5) << endl; // 41.3333 cout << "The integral of f(x)=x^3 between 1 and 5 is: " << integrate(cube, 1, 5) << endl; // 156 return 0; }
Code outline
In Integration wit ith fu function pointers
f(x) a b
- ffset = 0.001
double integrate(FUNC f, double a, double b){ //f is a pointer to the function of type //double function(double x) //use f(x)*offset to compute the area //of one slice; then sum up all slices. //x is the horizontal position of the //rectangle, and f(x) is the height. return area; }