回调函数的使用方法之例程说明

回调函数:假设A是回调函数,B是调用者,B参数里一个是指向A的函数指针,即回调A,同时另外的参数传递给A作为参数。A可以是多个函数的统一指向,只要函数参数一致即可。

WINDOWS回调函数:永远不会被程序中的其他函数或子程序调用。只能由操作系统调用。因此,windows可以通过传递不同参数给回调函数达到和程序沟通的目的。 

那么:B调用A,A也有参数,有参数就要赋值才行。所以B函数内部给A参数赋值。B调用A,A又利用了B给的参数

A就是回调函数。B就是调用者。

 
style="DISPLAY: none" id="api.blog.163.com" height="0" src="http://api.blog.163.com/crossdomain.html?t=20100205" width="0" name="api.blog.163.com"> style="DISPLAY: none" id="photo.163.com" height="0" src="http://photo.163.com/photo/html/crossdomain.html?t=20100205" width="0" name="photo.163.com"> style="DISPLAY: none" id="ud.blog.163.com" height="0" src="http://ud.blog.163.com/crossdomain.html?t=20100205" width="0" name="ud.blog.163.com">
#include<stdio.h>
#include<stdlib.h>

int (*ptr)(char *p);//函数指针的格式为,返回值类型 (*指针名)(参数列表)
typedef int (*pFunCallBack)(char *p); //利用类型定义,给函数指针类型取个别名/外号,注:利用类型定义有利于程序的移植

int Afun(char *p) 
{ 
	printf("Afun 回调打印出字符%s!\n", p);
	return 0;
}
int Cfun(char *p) 
{
	printf("Cfun 回调打印:%s, Nice to meet you!\n", p);

	return 0;
}


/*下面的这些是调用者:有几种方式*/
//方式1
int call1(pFunCallBack pCallBack, char *p)
{  
	pCallBack(p);

	return 0;
}

//方式2
int call2(char *p, pFunCallBack pCallBack)
{  
	pCallBack(p); 

	return 0;
}

//方式3
int call3(int (*ptr)(char *),char *p) 
{   
	(*ptr)(p);

	return 0;
}

//方式4
int call4(char *p, int (*ptr)(char *)) 
{   
	(*ptr)(p);

	return 0;
}

//验证小结的第三点结论,详细验证,相信你可以
void myFun(int a,int b)
{
	int t;
	t = a + b;
	printf("a + b = %d\n",t);
}
void call(int a,int b,int c,void (*pFun)(int a,int b))
{
	pFun(b,c);
}

int main()
{    
	char *p = "hello";

	printf("***********调用方式1*************\n");
	call1(Afun, p);	//调用Afun回调函数,传递参数*P给Afun函数
	call1(Cfun, p); //调用Cfun回调函数,传递参数*P给Afun函数
	printf("\n\n");

	printf("***********调用方式2*************\n");
	call2(p, Afun); //调用Afun回调函数,传递参数*P给Afun函数
	call2(p, Cfun); //调用Cfun回调函数,传递参数*P给Afun函数
	printf("\n\n");

	printf("***********调用方式3*************\n");
	call3(Afun,p);	//调用Afun回调函数,传递参数*P给Afun函数
	call3(Cfun,p);	//调用Cfun回调函数,传递参数*P给Afun函数
	printf("\n\n");

	printf("***********调用方式4*************\n");
	call4(p, Afun); //调用Afun回调函数,传递参数*P给Afun函数
	call4(p, Cfun); //调用Cfun回调函数,传递参数*P给Afun函数

	call(1,2,3,myFun);

	system("pause");

	return 0;
}

/*
小结:
	*  函数指针的格式为,返回值类型 (*指针名)(参数列表)
	*  调用函数声明函数指针的参数可采取两种方式,一种是直接定义,另外一种是利用typedef
	*  回调函数的参数的传递由调用函数来传递(之所以叫回调的原因就在于此,调用函数调用被调函数,被调函数又需要获取调用者的参数)
	传递的参数要么都在函数指针前或要么都在函数指针后,且都要紧挨着函数指针,且参数的类型及顺序要正确
*/

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值