指向函数的指针(pointers to functions)和回调函数
2014-11-27 14:15
405 查看
指向函数的指针主要用于*函数回调*。一言蔽之就是函数当做参数被调用。
可以像这样定义一个函数指针:
函数指针赋值:
也可以声明和赋值一块写:
下面使用函数指针作为参数(函数回调)来升序排序和降序排序一个数组
如果升序排序,那么比较函数指针compare应该接受一个这样的函数:
如果降序排序,那么比较函数指针compare应该接受一个这样的函数:
下面测试一下:
可以像这样定义一个函数指针:
int (*POINTER_NAME)(int a, int b)
函数指针赋值:
int func(int a,int b) { return a+b; } PINTER_NAME=func;
也可以声明和赋值一块写:
int (*POINTER_NAME)(int a,int b)=func
下面使用函数指针作为参数(函数回调)来升序排序和降序排序一个数组
// 使用经典的bubble sort排序 // compare函数指针用于接收比较函数 void bubble_sort(int* array,int count,int (*compare)(int,int)) { bool flag=true; for(int i=0;i<count;i++) { if(flag) { flag=false; for(int j=0;j<count-i-1;j++) { if(compare(array[j],array[j+1])>0) { int temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; flag=true; } } } else { break; } } }
如果升序排序,那么比较函数指针compare应该接受一个这样的函数:
int ascending_order(int a,int b) { return a-b; }
如果降序排序,那么比较函数指针compare应该接受一个这样的函数:
int descending_order(int a,int b) { return b-a; }
下面测试一下:
void print_array(int* array,int count) { for(int i=0;i<count;i++) { printf("%d ",array[i]); } printf("\n"); } int main() { int test_array[]={1,5,9,3,6,8}; bubble_sort(test_array,sizeof(test_array)/sizeof(test_array[0]),ascending_order); print_array(test_array,sizeof(test_array)/sizeof(test_array[0])); bubble_sort(test_array,sizeof(test_array)/sizeof(test_array[0]),descending_order); print_array(test_array,sizeof(test_array)/sizeof(test_array[0])); return 0; }
相关文章推荐
- [C++]C++ Pointers to functions 函数指针
- Pointers to Class Members Are Not Pointers(指向类成员函数的“指针”并非指针)
- const Pointers and Pointer to const Objects 常量指针和指向常量对象的指针
- Pointers to Class Members:指向类成员的指针
- Thinking in C++: Pointers to members 指向成员的指针
- Thinking in C++: Pointers to members 指向成员的指针
- const Pointers and Pointer to const Objects 常量指针和指向常量对象的指针
- 回调函数的实现(指向类成员函数的指针)
- 指向类成员的指针 (pointers to class members)
- 指向类成员的指针(Pointers to Class Members)
- Item 14. 函数指针(Function Pointers)
- 重新认识:指向函数的指针
- C/C++语言中指向函数的指针
- 封装回调函数——为对象方法(Object Method,参数中带this指针的函数) 构造 普通函数(参数中无this指针的函数)形式 的入口
- C/C++语言中指向函数的指针
- 指向成员函数的指针
- C++ Primer 指向成员函数的指针
- [转]C/C++语言中指向函数的指针
- C/C++语言中指向函数的指针
- C++和C里,指向函数的指针有所不同