通过宏定义声明结构体变量,避免了手工添加大量GetX, SetX函数。提供了封装性好,易访问的接口。
示例代码:
#include "stdafx.h"
#include <string>
#include <list>
//定义数据成员的宏定义,自动产生GetX, SetX函数
#define DECLARE_FIELD(Type, Attr) \
private: \
Type m_##Attr; \
public: \
const Type& Get##Attr()const\
{\
return m_##Attr;\
}\
void Set##Attr(const Type& value) \
{\
m_##Attr = value;\
}
class CParentNode
{
DECLARE_FIELD(int, AttrOne)
DECLARE_FIELD(std::string, AttrTwo)
};
//继承了CParentNode公有的GetX, SetX接口
class CSonNode:public CParentNode
{
DECLARE_FIELD(std::list<int>, AttrThree)
};
class CNode
{
DECLARE_FIELD(CSonNode, AttrFour)
DECLARE_FIELD(double, AttrFive)
public:
/*
由于AttrFour采用的是聚合的方式非继承,需要提供一步到位的获取数据接口。
避免客户代码写成这模样:X.GetA().GetB().GetC().GetD()......
*/
const int GetAttrOne()const{return m_AttrFour.GetAttrOne();}
const std::string& GetAttrTwo()const{return m_AttrFour.GetAttrTwo();}
const std::list<int>& GetAttrThree()const{return m_AttrFour.GetAttrThree();}
/*
提供一步到位修改数据的接口,避免客户代码写成这个模样:
CSonNode sonNode;
node.GetAttrFour(sonNode);
sonNode.SetAttrOne(10);
node.SetAttrFour(sonNode);
*/
void SetAttrOne(const int iValue){m_AttrFour.SetAttrOne(iValue);}
void SetAttrTwo(std::string& strValue){m_AttrFour.SetAttrTwo(strValue);}
void SetAttrThree(std::list<int>& lstValue){m_AttrFour.SetAttrThree(lstValue);}
};
int _tmain(int argc, _TCHAR* argv[])
{
//设置属性(获取属性类似)
CNode node;
node.SetAttrOne(10);
node.SetAttrTwo(std::string("123"));
node.SetAttrThree(std::list<int>(10, 11));
node.SetAttrFive(99.9);
return 0;
}