想要实现的效果就是如下这样获取和设置类的属性:
class A
{
private:
int x;
};
A a;
a.x = 1;
int b = a.x;
__declspec( property (put=setFunction, get=getFunction) ) data-type property-name;
通过几个宏包装一下:
#define PROPERTY(t,n) __declspec( property
( put = property__set_##n, get = property__get_##n ) ) t n;\
typedef t property__tmp_type_##n
#define READONLY_PROPERTY(t,n) __declspec( property (get = property__get_##n) ) t n;\
typedef t property__tmp_type_##n
#define WRITEONLY_PROPERTY(t,n) __declspec( property (put = property__set_##n) ) t n;\
typedef t property__tmp_type_##n
#define GET(n) property__tmp_type_##n property__get_##n()
#define SET(n) void property__set_##n(const property__tmp_type_##n& value)
private: int _x; public: PROPERTY(int, x); GET(x) { return _x; } SET(x) { _x = value; }
细节请见原文:http://www.codeproject.com/Articles/118921/C-Properties