文章目录
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;
}
在调用指针函数的时候应该使用引用参数作为传递。