函数指针,函数指针数组,以及回调函数(函数指针做函数参数)

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun01(int a,double b)
{
	printf("fun01:%d  %f\n", a,b);
}
void fun02(int a, double b)
{
	printf("fun02:%d  %f\n", a, b);
}
void fun03(int a, double b)
{
	printf("fun03:%d  %f\n", a, b);
}
//*********************函数指针*****************

void test01()
{
	//1. 定义函数指针类型
	typedef void(*TYPE1)(int, double);
	TYPE1 p1 = fun01;
	p1(10, 3.14);
	(*p1)(10, 3.14);
	//2. 先定义函数类型,通过类型定义指针
	typedef void(TYPE2)(int, double);
	TYPE2 *p2 = fun01;
	p2(20, 6.28);
	(*p2)(20, 6.28);
	//3. 直接定义函数指针变量
	void(*p3)(int, double) = fun01;
	p3(30, 9.14);
	(*p3)(30, 9.14);
}
//*********************函数指针数组*****************
//每个元素都是函数指针
void test02()
{
	//定义函数指针
#if 0
	void(*func[])(int, double) = { fun01, fun02, fun03 };
	int len = sizeof(func) / sizeof(func[0]);
	for (int i = 0; i < len; i++)
	{
		func[i](i + 10, i + 3.14);
		(*func[i])(i + 10, i + 3.14);
	}
#else
	void(*func[3])(int, double);
	func[0] = fun01;
	func[1] = fun02;
	func[2] = fun03;
	for (int i = 0; i < 3; i++)
	{
		func[i](i + 10, i + 3.14);
		(*func[i])(i + 10, i + 3.14);
	}

#endif
}
//*********************函数指针做函数参数(回调函数)*****************
int plus(int a, int b)
{
	return a + b;
}
int minus(int a, int b)
{
	return a - b;
}
//*****************************
int caculator(int a, int b, int(*func)(int, int))
{
	return func(a, b);
}
//*****************************
typedef int(*TYPE)(int, int);
int my_caculator(int a, int b, TYPE func)
{
	return func(a, b);
}
//****************************************
void test03()
{
	int result = caculator(10, 20, plus);
	printf("%d\n", result);
	result = my_caculator(20, 15, minus);
	printf("%d\n", result);
}
void main()
{
	//test01();
	//test02();
	test03();
	system("pause");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值