用 C# 或者 Borland C++ Builder 的时候会遇见“property”这个东西,可以控制读写方式。标准 C++ 并没有这个概念,那么我们能否在纯 C++ 中使用这个功能呢?当然可以。下面是本人独立完成的一个实现方法:
#include <iostream>
using namespace std;
typedef enum {READONLY, READWRITE} RW_Right;
template <class _Class /* 包含该属性的类 */ ,
typename _Ty /* 该属性的类型 */,
RW_Right = READWRITE /* 该属性的权限:默认为读写 */ >
class Property
{
public:
typedef _Ty* (_Class::*Getter)(void);
typedef void (_Class::*Setter)(const _Ty&);
public:
Property(_Class& _src /* 目标对象*/,
const Getter _getter /* 取值函数 */,
const Setter _setter /* 赋值函数 */)
:m_src(_src), m_getter(_getter), m_setter(_setter)
{}
operator _Ty&() /* 返回 lvalue */
{
return *(m_src.*m_getter)(); /* 可以直接对原始数据赋值 */
}
operator const _Ty&() const
{
return *(m_src.*m_getter)();
}