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 本文出自 “AI-Life” 博客,请务必保留此出处http://ai00life.blog.51cto.com/2198685/1932493 |
|