C++函数指针、回调函数、指针函数

1、函数指针和回调函数

示例:

typedef int (*a) ();
int foo(){}
a f = foo;

(*f)();
等价于
foo();

typedef int (*a) ();定义参数为空,返回值为int类型的函数指针类型a,常用于在回调中使用,等价于

typedef int (*) foo;

去掉修饰符typedef和别名,则为int (*)()类型,前面为返回值,后面为输入参数。int (*)(int,int)则表示输入参数为int,int类型,返回为int类型的函数指针,可以用于指向具有相同返回类型和输入参数的函数。因此回调函数可以使没有返回值的函数产生返回值

例如:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
using namespace std;

typedef int(*a) ();

int hello()
{
	printf("hello\n");
	return 1;
}

int world()
{
	printf("world\n");
	return 0;
}

void IuseCallBack(a callback)
{
	int retval = callback();
	printf("%d", retval);
}


int main()
{
	IuseCallBack(hello);
	system("pause");
}

使用IuseCallBack(hello)或IuseCallBack(world)可以打印出"hello"或"world"。

2、指针函数

  指针函数为返回值是指针的函数。
  示例代码:

int *max(int *p,int *q)
	{
		if ( *p > *q )
		{
			return p;
		}
		else
		{
			return q;
		}
	}

int main()
{
	int *point, a, b;
	a = 3, b = 4;
	point = max(&a, &b);
	std::cout << *point << std::endl;
}

  在调用指针函数的时候应该使用引用参数作为传递。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

面条有点辣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值