回调函数

来源:互联网 发布:淘宝支付网站 编辑:程序博客网 时间:2024/06/13 08:52
函数指针做参数

       int  getValue(int  a, int  b, int  (*p)(int , int));

       getValue: 函数名

       int (*p)(int ,int): 函数指针做getValue函数的参数

       int  value = getValue(3, 6, maxValue);(函数调用:getValue函数执行过程中再调用(回调)maxValue)

例子:写一个函数查找成绩在90以上的,使用回调函数在名字后面加上高富帅。

#import <Foundation/Foundation.h>
//定义一个学生结构体
typedef struct stu{
    char name[20];
    int  age;
    int score;
}Stu;

//声明一个函数,对对一个stu数组进行比较,及字符连接
void sort(Stu stu[],int count)
{
    for (int i = 0;i < count ;i++) {
        if (stu[i].score > 90) {
         strcat(stu[i].name, "*高富帅");
            
            }
        }
    
}

//声明一个函数,实现将Stu结构体数组比较,及字符连接好在输出
void ShowStudents(Stu stu[],      //我们要操作的数据
                 int count,       //数据的辅助属性
                  void (*p) (Stu stu[],int count)     //一些繁琐的功能抽离出来交给其他人做

                 )
{
 
    //需要对stu进行比较,及字符连接
    p(stu,count);
    
     //现将学生信息打印到控制台,模拟核心代码
    for (int i =0;i < count; i++) {
        Stu temp = stu[i];
        printf("%s--%d--%d\n",temp.name,temp.age,temp.score);
    }

}
int main(int argc, const char * argv[])
{

    
    Stu students[5] = {
        {"xulixia",22,87.0},
        {"jingjing",23,78.5},
        {"xujie",23,98.8},
        {"menhao",26,92.1},
        {"benfang",24,93.9}
    };
    
    void (*p) (Stu student[],int count) = NULL;  //声明一个排序指针
    
    p = sort;  //将函数赋值到函数指针上
    
    ShowStudents(students,5,p);   //利用函数指针为核心代码系统进行排序
    
    return 0;
}

0 0
原创粉丝点击