使用函数指针优化重复代码

未简化前代码:

#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行,是不是要清爽多了呢?如果相关联函数和重复代码过多的情况,使用这种方式可以极大地实现代码降重,是不是很巧妙呢?这里只提供思路,脑洞大的作者可以通过对这种方式的学习迁移到自己的项目上进行优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值