lab 10 function pointer
play

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


  1. Lab 10

  2. 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.

  3. 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);

  4. Function Pointer Example

  5. Function Pointer Example

  6. Function Pointer Example

  7. Function Pointer Example

  8. Function Pointer //declaring a pointer to function: //existing functions: int (*f1)(); int function1(){ ... } int (*f2)(int); int function2(int x){ ... } Int (*f3)(int, int); int function3(int x,int y){ ... } int (*f4)(int *); int function4(int *x){ ... }

  9. #include <iostream> using namespace std; Code outline 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; }

  10. In Integration wit ith fu function pointers 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. f(x) //x is the horizontal position of the //rectangle, and f(x) is the height. return area; } a b offset = 0.001

Recommend


More recommend