1: function pointer pointer to function memory, a function at compile time is assigned to a portal address, the function of the entry address is called the function pointer. You can use a pointer variable to point to a function, and then call this function from that pointer variable.
A function can return an integer value, a character value, a real value, and so on, or it can return a pointer-type data, that is, an address, and the type of the return value is a pointer type. Returns a pointer function that is worthy of a function abbreviation.
The general form of defining pointer functions is:
Type name * Function name (parameter list)
For example, define a pointer to a function with two parameters and a return value and a function with the same return value parameter list as follows:
int sum (int x,inty);
int *a (int,int);
A=sum;
A function pointer can point to a function that returns a value and a parameter list, when a function pointer is used, as follows:
int c,d;
*a (C,D);
2: Use the function pointer for the calculation, the code is as follows:
//ConsoleApplication5.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>using namespacestd;intAvgintAintb);intSumintAintb);intMain () {intiwidth, Ilenght, Iresult; Iwidth=Ten; Ilenght=Ten; int(*pfun) (int,int);//Defining function Pointerscout <<"the Pfun points to avg"<<Endl; Pfun=avg; Iresult= (*pfun) (iwidth, ilenght);//calling functions with function pointerscout <<"Execution Result:"<< Iresult <<Endl; cout<<"Pfun points to the sum"<<Endl; Pfun=sum; Iresult= (*pfun) (iwidth, ilenght);//calling functions with function pointerscout <<"Execution Result:"<< Iresult <<Endl; return 0;}intSumintAintb) { returnA +b;}intAvgintAintb) { return(A + B)/2;}View Code
Operation Result:
Introduction to C + + Classic-Example 5.8-using pointer functions for operations