Gemery

导航

VC++属性器

      用VC++在开发项目中,有时候一个项目存在很多实体,每个实体都有若干个属性,加入属性器之后,

在实体类中就不用重复的添加Set 或 Get函数。 属性允许用Get函数去访问,也可以用Set函数去写属性,

但是有时候,某些属性只允许去读而不允许写,为了能够在类中清楚的表达这个意思我引入了属性器的概念。

使用属性器需要引入一下这个头文件:

gxx_property.h

#pragma once
#define GPropertyClass // 说明声明的类具有属性

#define GPropertyReadOnly(name,type) \
private:\
type name;\
public: const type Get##name()\
{\
return name;\
}
#define GProperty(name,type) \
private:\
type name;\
public: const type Get##name()\
{\
return name;\
}\
public: void Set##name(const type& newVar )\
{\
name
= newVar;\
}\
public: type& Set##name()\
{\
return name;\
}
#define GPropertyInit(name,value) \
name
= value;
#define GPropertyInit2(P1,P2,V1,V2) \
GPropertyInit(P1,V1);\
GPropertyInit(P2,V2);
#define GPropertyInit3(P1,P2,P3,V1,V2,V3) \
GPropertyInit(P1,V1);\
GPropertyInit2(P2,P3,V2,V3);
#define GPropertyInit4(P1,P2,P3,P4,V1,V2,V3,V4) \
GPropertyInit(P1,V1);\
GPropertyInit3(P2,P3,P4,V2,V3,V4);

#define GET(name) \
Get##name()
#define SET(name) \
Set##name()

使用方法:

class GPropertyClass CPeople
{
public :
  CPeople();
  GPropertyReadOnly(Name, CString) ; // 姓名
   GPropertyReadOnly(Sex, bool); // 性别, true:男, false:女
   GPropertyReadOnly(ID, CString); // 身份证ID
  GProperty(Age,
int); // 年龄
GProperty(Address, CString); // 住址
   GProperty(Favorite, CString); // 爱好

...
};

CPeople::CPeople()
{
// 初始化属性
  GPropertyInit3(Name, Sex, ID, _T(
"张三"),true,_T("2031224222444555));
  GPropertyInit3(Age, Address, Favorite, 25, _T("北京"), _T("旅游"));
}

// 测试访问
void Test()
{
  CPeople onePeople;
  onePeople.GetName(); // 正确
  onePeople.SetName(_T("李四")); // 出错
  onePeople.GetAge();
// 正确
  onePeople.SetAge(26); // 他长大了一岁, 正确

  CString strFac
= onePeople.GetFavorite();
  strFac
+= _T(",看电影");
  onePeople.SetFavorite( strFac );
  // 用宏去操作属性
onePeople.SET( Favorite ) += _T(",骑自行车");
  CString strOut
= onePeople.GetName();
  strOut += _T("的爱好有:") + onePeople.GetFavorite();
  TRACE(strOut); // 张三的爱好有: 旅游,看电影,骑自行车

}

当我们试图去设置一个只读属性的时候,程序编译将会失败. 使用属性器后,属性的运用更加明确,减少了代码量,便于修改属性

的类型.

     我在工作中已经大量的运用了这几个属性控制宏, 使得我的程序更容易维护。

     在声明一个类时定义 GPropertyClass,说明这个类使用到了属性控制, GPropertyClass并没有什么实际意义。

posted on 2011-05-16 17:00  Gemery  阅读(328)  评论(1编辑  收藏  举报