现在的位置: 首页 > 综合 > 正文

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

2018年03月18日 ⁄ 综合 ⁄ 共 1040字 ⁄ 字号 评论关闭

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

界面显示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;
}

抱歉!评论已关闭.