zoukankan      html  css  js  c++  java
  • 回调函数用法范例

      回调函数是指 使用者自己定义一个函数,实现这个函数的程序内容,然后把这个函数(入口地址)作为参数传入别人(或系统)的函数中,由别人(或系统)的函数在运行时来调用的函数。

      函数是你实现的,但由别人(或系统)的函数在运行时通过参数传递的方式调用,这就是所谓的回调函数。简单来说,就是由别人的函数运行期间来回调你实现的函数

    范例一:

    #include <stdio.h>

    #define CALLBACK
    CALLBACK void Printnum(int num)
    {
    printf("num is %d ",num);
    }

    CALLBACK void Printstr(char *buf)
    {
    printf("%s ",buf);
    }

    void showNum(void (* ptr)(),int n)
    {
    (* ptr)(n);
    }


    void showstr(void (*ptr)(),char *buf)
    {
    (*ptr)(buf);
    }

    int main(int argc, char* argv[])
    {
    char buf[32]="hello,world!";
    showstr(Printstr,buf);
    showNum(Printnum,5);
    return 0;
    }

    范例二:

    #include <stdio.h>

    #define CALLBACK
    struct operation {
    void (*callback)();
    };

    void trigger(struct operation* ops, int ops_length) {
    int i = 0;
    while(i++ < ops_length) {
    ops->callback();
    ops++;
    }
    }

    CALLBACK void a_callback() {
    printf("I'm A ");
    }

    CALLBACK void b_callback() {
    printf("I'm B ");
    }

    int main(int argc, char* argv[])
    {
    struct operation A,B;
    A.callback = &a_callback;
    B.callback = &b_callback;
    struct operation ops[2];
    ops[0] = A;
    ops[1] = B;
    trigger(ops, 2);
    return 1;
    }

  • 相关阅读:
    大数问题(三)(大数相除)
    直接插入排序的四种实现方法
    蟠桃记
    杭电oj find your present (2)
    CSS中的class与id区别及用法
    史上最全的css hack(ie6-9,firefox,chrome,opera,safari) (zz)
    CSS之CSS hack
    HTML语言的一些元素(五)
    HTML语言的一些元素(四)
    HTML语言的一些元素(三)
  • 原文地址:https://www.cnblogs.com/baiduboy/p/8405011.html
Copyright © 2011-2022 走看看