您的位置:首页 > 其它

如何使用指向函数的指针

2014-08-09 15:37 274 查看
在使用指向函数的指针调用函数时,可以使用两种形式:

定义:int (*fun)(int a,int b);

赋值:fun = fun1;

调用:fun(a,b);或者(*fun)(a,b);均可。

下面是测试程序:(Visual Studio 2013)

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int add(int x, int y)
{
return x + y;
}

int minus(int x, int y)
{
return x - y;
}

int compute(int x, int y, int(*f)(int x, int y))
{
//return f(x, y);
return (*f)(x, y);
//使用上述两种情况均可。
}

int main()
{
int x, y;
char z;
int n;
while (1)
{
printf("input:");
scanf("%d%c%d", &x, &z, &y);
switch (z)
{
case '+':
n = compute(x, y, add);
break;
case '-':
n = compute(x, y, minus);
break;
default:
break;
}
printf("%d\n", n);
}
return 0;
}

测试结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: