c语言map函数指针,函数指针 - 弧光守望者 - OSCHINA - 中文开源技术交流社区

这篇博客介绍了如何使用C/C++中的函数指针和switch语句实现运算符重载,通过FunctionMap函数根据输入的运算符选择相应的数学运算函数。作者举例了加、减、乘、除四种基本运算,并展示了运行结果。
摘要由CSDN通过智能技术生成

/*Author:Choas Lee

*Date:2012-02-28

*/

#include

#include

#include

float add(float a,float b){return a+b;}

float minus(float a,float b){return a-b;}

float multiply(float a,float b){return a*b;}

float divide(float a,float b){return a/b;}

//该函数的返回值是一个函数

float(* FunctionMap(char op) )(float,float)

{

switch(op)

{

case '+':

return add;

break;

case '-':

return minus;

break;

case '*':

return multiply;

break;

case '\\':

return divide;

break;

default:

exit(1);

}

}

int main()

{

float a=10,b=5;

char ops[]={'+','-','*','\\'};

int len=strlen(ops);

int i=0;

float (*returned_function_pointer)(float,float);//定义了一个函数指针

for(i=0;i

{

returned_function_pointer=FunctionMap(ops[i]);

printf("the result caculated by the operator %c is %f\n",ops[i],returned_function_pointer(a,b));

}

return 0;

}

输出:

the result caculated by the operator + is 15.000000

the result caculated by the operator - is 5.000000

the result caculated by the operator * is 50.000000

the result caculated by the operator \ is 2.000000

参考:

1.http://hipercomer.blog.51cto.com/4415661/792301

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值