本人在C++项目中经常需要用到get和set方法,但是c++并不像 java的eclipse有自动生成 get 和 set 方法。如果手写是可以,但是当属性特别多的时候会非常麻烦。。。于是决定使用宏定义方法来解决。
本人在参考了网上资料(参见文章末尾的参考文献)之后,实现了自己的版本,cplusplusgetset.h头文件如下:
#pragma once
//PropertyBuilderByTypeName 用于生成类的成员变量
//并生成set和get方法
//variable_type为变量类型,可以是指针类型,也可以是非指针类型,例如int,int*等
//type_shortname为变量类型的缩写,例如bool缩写为b,int缩写为i,double缩写为d等
//method_name为方法名称
//access_permission为变量的访问权限(public, protected, private)
#define PropertyBuilder_ReadWrite(variable_type, type_shortname, method_name, access_permission)\
access_permission:\
variable_type m_##type_shortname##method_name;\
public:\
inline variable_type get##method_name(void)\
{\
return m_##type_shortname##method_name;\
}\
inline void set##method_name(variable_type v)\
{\
m_##type_shortname##method_name = v;\
}\
#define PropertyBuilder_ReadOnly(variable_type, type_shortname, method_name, access_permission)\
access_permission:\
variable_type m_##type_shortname##method_name;\
public:\
inline variable_type get##method_name(void) const\
{\
return m_##type_shortname##method_name;\
}\
#define PropertyBuilder_WriteOnly(variable_type, type_shortname, method_name, access_permission)\
access_permission:\
variable_type m_##type_shortname##method_name;\
public:\
inline void set##method_name(variable_type v)\
{\
m_##type_shortname##method_name = v;\
}\
使用说明:
class MyClass
{
public:
MyClass()
{
m_bLookAhead = true;
m_dStatus = NULL;
m_iHello = 0;
}
~MyClass() {}
PropertyBuilder_ReadWrite(bool, b, LookAhead, protected)//bool m_bLookAhead;
PropertyBuilder_ReadWrite(double*, d, Status, protected)//bool* m_pStatus;
PropertyBuilder_WriteOnly(int, i, Hello, private)//int m_iHello;
public:
void test()
{
setLookAhead(true);
double a = 0;
setStatus(&a);
setHello(5);
bool r = getLookAhead();
}
};
---
参考文献
www.codeproject.com/Articles/11…