函数指针和函数引用
    norm_ptr is a pointer, a function pointer.
    The function should have two float parameters, and returns float.

    函数指针也是一个指针,指向函数,指向的是执行指令的地址;之前的指针指向的都是内存的数据

    1. #include <iostream>
    2. #include <cmath>
    3. using namespace std;
    4. float norm_l1(float x, float y); //declaration
    5. float norm_l2(float x, float y); //declaration
    6. float (*norm_ptr)(float x, float y); //norm_ptr is a function pointer
    7. int main()
    8. {
    9. norm_ptr = norm_l1; //Pointer norm_ptr is pointing to norm_l1
    10. cout << "L1 norm of (-3, 4) = " << norm_ptr(-3.0f, 4.0f) << endl; // function invoked
    11. norm_ptr = &norm_l2; //Pointer norm_ptr is pointing to norm_l2
    12. cout << "L2 norm of (-3, 4) = " << (*norm_ptr)(-3.0f, 4.0f) << endl;
    13. return 0;
    14. }
    15. float norm_l1(float x, float y)
    16. {
    17. return fabs(x) + fabs(y);
    18. }
    19. float norm_l2(float x, float y)
    20. {
    21. return sqrt(x * x + y * y);
    22. }

    常用案例:
    A function pointer can be an argument and pass to a function.
    把函数当作一个参数传递给另外一个参数

    1. // <stdlib.h>
    2. void qsort
    3. ( void *ptr, size_t count, size_t size,
    4. int (*comp)(const void *, const void *) // 自定义该排序标准的算法
    5. );

    To sort some customized types, such as

    • struct Point
    • struct Person

    Function references

    1. #include <iostream>
    2. #include <cmath>
    3. using namespace std;
    4. float norm_l1(float x, float y); //declaration
    5. float norm_l2(float x, float y); //declaration
    6. float (&norm_ref)(float x, float y) = norm_l1; //norm_ref is a function reference
    7. int main()
    8. {
    9. cout << "L1 norm of (-3, 4) = " << norm_ref(-3, 4) << endl;
    10. return 0;
    11. }
    12. float norm_l1(float x, float y)
    13. {
    14. return fabs(x) + fabs(y);
    15. }
    16. float norm_l2(float x, float y)
    17. {
    18. return sqrt(x * x + y * y);
    19. }