Java C C++回调函数

1、定义CALLBACK类型的函数指针   typedef int (CALLBACK*)(int x, int y)


2、定义函数method,将CALLBACK类型的函数指针作为函数参数   void method(CALLBACK FP, int a, int b)

void method(CALLBACK FP, int a, int b)

{

    FP(a, b);

}


3、定义main函数,调用method方法

int main()

{

    // 调用method方法需要参数FP,所以自己写一个该类型的函数,就实现回调了

    int ret = method(add, 3, 5)

    return 0;

}


4、int (*add)(int x, int y)

{

    return x + y;

}




java中用接口模拟函数指针实现第一步

public interface FunctionPoint {

    int callback(int x, int y);

}


定义一个类,将该接口对象作为方法参数实现第二步

public class Function {

    public int method(FunctionPoint FP, int x, int y) {

        FP.callback(x, y);

    }

}


定义带main方法的类

public class CalllBack implements FunctionPoint {

    public static void main(String[] args) {

        // 调用method方法

        Function f = new Function();

        f.method(new imp(), 2, 5);

    }    

}


public class imp implements FunctionPoint {

    public int callback(int x, int y) {

        return x + y;

    }

}



C++回调参考:http://blog.csdn.net/xie1xiao1jun/article/details/8262902


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章