未简化前代码:
#include <lontern.h>
typedef struct _score
{
float chinese;
float math;
float english;
}score;
score s1 = { 80,90,95 }, s2 = { 85,85,98 };
void relate_chinese(score s1, score s2) {
if (s1.chinese < s2.chinese) {
cout << "省略1W行相同代码....";
}
}
void relate_math(score s1, score s2) {
if (s1.math == s2.math) {
cout << "省略1W行相同代码....";
}
}
void relate_english(score s1, score s2) {
if (s1.english > s2.english) {
cout << "省略1W行相同代码....";
}
}
int main() {
int i = 0;
puts("请输入数字进入相应流程!");
cin >> i;
switch (i) {
case 1:
relate_chinese(s1, s2);
break;
case 2:
relate_math(s1, s2);
break;
case 3:
break;
relate_english(s1, s2);
}
}
看到代码我们思考一个问题,相关联的几个函数当中每个函数假设存在1万行相同代码,不同的地方仅仅就是一个判断,此时如何去掉这些重复代码,进行优化呢?这里我们可以使用函数指针来完成。
优化后的代码
#include <lontern.h>
typedef struct _score
{
float chinese;
float math;
float english;
}score;
score s1 = { 80,90,95 }, s2 = { 85,85,98 };
typedef int (*funcion_ptr)(score s1, score s2);
int by_chinese(score s1, score s2) {
return s1.chinese < s2.chinese;
}
int by_math(score s1, score s2) {
return s1.math == s2.math;
}
int by_english(score s1, score s2) {
return s1.english > s2.english;
}
void relate(funcion_ptr func_p) {
if ((func_p)(s1,s2)){
cout << "省略1W行相同代码....";
}
}
int main() {
int i = 0;
puts("请输入数字进入相应流程!");
cin >> i;
funcion_ptr funtions[3] = {by_chinese ,by_math,by_english};
if (i > 0 && i < 4) {
relate(funtions[i - 1]);
}
}
通过函数指针,我们把原本3W行的代码优化成了1W行,是不是要清爽多了呢?如果相关联函数和重复代码过多的情况,使用这种方式可以极大地实现代码降重,是不是很巧妙呢?这里只提供思路,脑洞大的作者可以通过对这种方式的学习迁移到自己的项目上进行优化。