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