函数指针和函数引用norm_ptr is a pointer, a function pointer.
The function should have two float parameters, and returns float.
函数指针也是一个指针,指向函数,指向的是执行指令的地址;之前的指针指向的都是内存的数据
#include <iostream>#include <cmath>using namespace std;float norm_l1(float x, float y); //declarationfloat norm_l2(float x, float y); //declarationfloat (*norm_ptr)(float x, float y); //norm_ptr is a function pointerint main(){norm_ptr = norm_l1; //Pointer norm_ptr is pointing to norm_l1cout << "L1 norm of (-3, 4) = " << norm_ptr(-3.0f, 4.0f) << endl; // function invokednorm_ptr = &norm_l2; //Pointer norm_ptr is pointing to norm_l2cout << "L2 norm of (-3, 4) = " << (*norm_ptr)(-3.0f, 4.0f) << endl;return 0;}float norm_l1(float x, float y){return fabs(x) + fabs(y);}float norm_l2(float x, float y){return sqrt(x * x + y * y);}
常用案例:
A function pointer can be an argument and pass to a function.
把函数当作一个参数传递给另外一个参数
// <stdlib.h>void qsort( void *ptr, size_t count, size_t size,int (*comp)(const void *, const void *) // 自定义该排序标准的算法);
To sort some customized types, such as
- struct Point
- struct Person
Function references
#include <iostream>#include <cmath>using namespace std;float norm_l1(float x, float y); //declarationfloat norm_l2(float x, float y); //declarationfloat (&norm_ref)(float x, float y) = norm_l1; //norm_ref is a function referenceint main(){cout << "L1 norm of (-3, 4) = " << norm_ref(-3, 4) << endl;return 0;}float norm_l1(float x, float y){return fabs(x) + fabs(y);}float norm_l2(float x, float y){return sqrt(x * x + y * y);}
