程序运行后,操作系统会为其分配一块内存空间,用于存放程序本身的代码及其需要的数据(分区存放,还有一块空闲的堆空间)。程序的标识符(诸如变量、函数名等)是这一块内存空间中命名的、连续的一个内存空间的地址。而指针就可以存储一个这样的地址,指针可以是动态申请的堆空间返回的地址,也可以是变量命名的内存空间,也可以是函数名表示的函数代码存储的空间(称为函数指针,一个指向函数体存储空间的指针)。不管是指针变量还是函数指针都可以作为函数的参数,这样的好处是形成统一的接口,形成对函数的调用。
形参的一般的定义格式如下:(使用一个函数名就可以将形参初始化为实参)
double(*pfun)(double) //注意与double *pfun (double)相区别, (double)表示是一个函数定义,其优先级高于指针,所以从左到右可以读为指针函数,表示一个返回指针的函数。而double(*pfun)(double)前面(*pfun)的()是用于提升优先级的操作符,所以可以将其读到最后,也就是函数指针,一个指向函数的指针。
如有如下任务:求一个数组的元素的平方和和立方和,便可以采用分治的方法,一个函数求平方,一个函数求立方,一个函数求和,求和的函数使用一个函数指针作为参数,以分别用于求平方和和立方和。
// A pointer to a function as an argument #include <iostream> //#include <math.h> using std::cout; using std::endl; // Function prototypes double squared(double); double cubed(double); double sumarray(const double data[], size_t len, double(*pfun)(double)); int main() { double data[] = {1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5}; int len = 7; cout << endl << "Sum of squares = " << sumarray(data, len, squared); cout << endl << "Sum of cubes = " << sumarray(data, len, cubed); cout << endl; std:: cin.get(); return 0; } // Function for a square of a value double squared(double x) { return x*x; } // Function for a cube of a value double cubed(double x) { return x*x*x; } // Function to sum functions of array elements double sumarray(const double data[], size_t len, double(*pfun)(double)) { double total = 0; // Accumulate total in here for (size_t i=0; i < len; i++) total += pfun(data[i]); return total; }
输出:
Sum of squares = 169.75 Sum of cubes = 1015.88
-End-