属性的基本特征就是拥有getter、setter。
C++中基本上把实现一个类的赋值运算符、类型转换运算符就能实现属性的特征,而在类型方面,使用模板便可以处理任意类型:
namespace extension
{
template<typename T> struct property
{
protected:
public:
property() = default;
property(const property<T>& _pt) : __t(_pt) {}
property(property<T>&& _pt) noexcept : __t(_pt) {}
property(const T& _t) : __t(_t) {}
property(T&& _t)noexcept : __t(_t) {}
T& operator=(const T& _t)
{
__t = _t;
return __t;
}
T& operator=(T&& _t) noexcept {
__t = _t;
return __t;
}
T& operator=(const property<T>& _t)
{
__t = _t;
return __t;
}
T& operator=(property<T>&& _t) noexcept {
__t = _t;
return __t;
}
operator T() const { return __t; }
private:
T __t;
};
}
struct MyStruct
{
property<int> num = 9;
};
int main()
{
MyStruct ms;
cout << ms.num << endl;
ms.num = 10;
cout << ms.num << endl;
property<int> i = 90;
ms.num = i;
cout << ms.num << endl;
property<int> y(i);
cout << y << endl;
return 0;
}