巧用成员指针减少代码重复

如今,大多软件将界面和业务逻辑进行分离,达到一个松耦合的效果。但由于思考出发点不同将会发生如下问题:

界面显示5条格式类似的数据,于是,界面侧设计了如下结构用于存储此5条数据:

struct Screen {
	int line1;
	int line2;
	int line3;
	int line4;
	int line5;
};

于是,业务逻辑层只能通过如下方法进行设置:

Screen screen;
screen.line1 = 1;
screen.line2 = 2;
screen.line3 = 3;
...
setScreen(screen);
实际每一行的数据顺序地进行存储,从而顺序读出,所以业务逻辑层希望写出如下代码:

for(int i = 0; i < 5; ++i) {
        screen.line[i] = getLine(i);
}
由于UI层设计的结构并非采用数组结构,不能进行循环,于是,我们便在业务层中将其转化为数组,小小利用下成员指征便可完成上述想法。

#include <iostream>

struct Screen {
	int line1;
	int line2;
	int line3;
	int line4;
	int line5;
};
typedef int Screen::*Screen_Line;

int getLine(int line) {
	return line;
}

int main()
{
	//重映射成员指针数组
	Screen_Line memArray[5] = {
	       	&Screen::line1,
	       	&Screen::line2,
	       	&Screen::line3,
	       	&Screen::line4,
	       	&Screen::line5,
       		};

	Screen testStruct;
	//下面即可采用循环进行设置
	for (int i = 0; i < 5; ++i) {
		testStruct.*memArray[i] = getLine(i);
	}
	
	std::cout << "Screen::line1 : " << testStruct.line1 << std::endl;
	std::cout << "Screen::line2 : " << testStruct.line2 << std::endl;
	std::cout << "Screen::line3 : " << testStruct.line3 << std::endl;
	std::cout << "Screen::line4 : " << testStruct.line4 << std::endl;
	std::cout << "Screen::line5 : " << testStruct.line5 << std::endl;

	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值