Java C C++回调函数

本文通过示例详细介绍了如何在C++与Java中实现回调机制。C++部分使用函数指针,Java部分则利用接口来模拟函数指针的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.youkuaiyun.com/xie1xiao1jun/article/details/8262902

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值