c++编程之回调函数

回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

下面两个实例

c++代码

//回调函数测试用例
#include "stdafx.h"
#include<stdio.h>
/*serer 端程序*/
int (*g_pFun)(int x, int y);
//执行函数,内部调用回调函数
int plat()
{
	int r;
	int a = 10;
	int b =15;
	r = g_pFun(a,b);//回调函数
	printf("%d\n", r);
	return 0;
}


/*client端实现代码*/
//注册函数
int RegFun(int (*pFun)(int x, int y))
{
	g_pFun = pFun;
	return 0;
}

int Max(int x, int y)
{
	return x > y ? x : y;
}
int Min(int x, int y)
{
	return x > y ? y : x;
}
int main(void)
{
	RegFun(Max);//注册函数Max
	plat();//执行函数
	RegFun(Min);//注册函数Min
	plat();
	return 0;
}



java代码

package test;


import caller.caller;
import MyCallInterface.MyCallInterface;
public class mytest implements MyCallInterface{
	public void method()
	{
		System.out.println("回调");
	}
	public static void main(String args[])
	{
		caller call = new caller();
		call.setCallfuc(new mytest());
		call.call();
	}


}

package MyCallInterface;


public interface MyCallInterface {


	public void method();
}

package caller;
import MyCallInterface.MyCallInterface;
public class caller {
	public MyCallInterface mc;
	public void setCallfuc(MyCallInterface mc)
	{
		this.mc = mc;
	}
	public void call()
	{
		this.mc.method();
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值