在C/C++中,switch语句是经常被用到的,当switch内的case语句较多时程序有时显得比较繁乱,此种情况下可以用另外一种实现方式替代switch。详细用法见例子:
#include "stdafx.h"
float AddFunc(float a, float b)
{
return (a + b);
}
float SubFunc(float a, float b)
{
return (a - b);
}
float MultiplyFunc(float a, float b)
{
return (a * b);
}
float DivisionFunc(float a, float b)
{
return (a / b);
}
void Fun1(float a, float b, int flag, float &result)
{
switch (flag)
{
case 0:
result = AddFunc(a, b);
break;
case 1:
result = SubFunc(a, b);
break;
case 2:
result = MultiplyFunc(a, b);
break;
case 3:
result = DivisionFunc(a, b);
break;
}
}
//若函数无参数,且返回值为空,则应该这样定义:
//typedef void (*BasicOperationsFunc)();
typedef float (*BasicOperationsFunc)(float a, float b);
BasicOperationsFunc g_BasicOperationsFunc[] = {
&AddFunc,
&SubFunc,
&MultiplyFunc,
&DivisionFunc
};
void Fun2(float a, float b, int flag, float &result)
{
BasicOperationsFunc basicOperationFunc = g_BasicOperationsFunc[flag];
if (!basicOperationFunc) return;
result = basicOperationFunc(a, b);
}
int _tmain(int argc, _TCHAR* argv[])
{
float a = 10, b = 2;
float result1 = 0, result2 = 0;
int flag = 1;
Fun1(a, b, flag, result1);
Fun2(a, b, flag, result2);
return 0;
}
首先声明一个BasicOperationsFunc,然后定义一个BasicOperationsFunc类型的数组,这样在Fun2函数中就可以不用switch,而直接通过basicOperationFunc来调用相应的函数即可。如果在case条件比较多的情况下,这是一种不错的替代方法。
还有其它推荐的方法吗?