C++模拟C#属性机制

本文探讨了如何在C++中模拟C#的属性特性,包括数据验证、内部状态更新等,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用了两年C#,感觉C#跟C++来比毕竟是新生儿,吸取了前辈的优点,为程序员带了来很多便利,这两天又写C++的程序,感觉很多地方不如C++方便,今天就凑空研究了一下C++模拟C#中的属性,因为C#中的属性可以分别通过属性控制一个字段的读写操作,具有一些优点:
(1)写操作可以对客户代码传入的数据进行检验。比如对数值范围的检验,字符串空的检验等。
(2)写操作时,可以同步对其它内部状态进行更新。比如一个文档类,如果改变了其行宽,那么每行内可以容纳的字符数肯定要更新。
(3)读操作时,可以按需生成数据。比如生成一个要读取的数据在初始化时并没有生成,而且生成一次的CPU资源消耗很大,并且这些操作并不是经常用到,于是便可以在第一次读到时才生成这些数据并存储,以后就不用再进行操作。
(4)语句简洁。使用属性时,可以像使用字段一样方便,无需添加括号,看起来也比较符合人的习惯。比如Pepole.Name看起来要比Pepole.GetName()要舒服得多了。
当然,获得这些优点的同时也需要付出代价的,那就是损失一些性能,因为属性的读写操作就是操作函数,当然要比直接使用变量多消耗一些调用和堆栈操作的时间,我曾经在C#中测试过List.Length,如果操作次数过于频繁的话,这点性能损失还是不可忽略的,具体可以看以前我写的一篇博客文章。
下面是具体实现的一些代码,代码内含注释,就无需多说,因为我相信这么一句话--“代码中没有任何秘密可言”,原句可能不是这样,也不记得誰说的了,反正意思差不多。

#include 
#include 
#include 
#include 
#include using namespace std; #pragma warning(disable:4010) /// InvalidValueException class InvalidValueException : public exception { public : /// for build-in types template InvalidValueException(const T i) { msg= new char[BUFF_SIZE]; sprintf_s(msg,BUFF_SIZE, "Invalid Value : %d ", i); } InvalidValueException(const string& v) { /// Here, you can't call /// InvalidValueException(const char* pc) /// like c#, If another constructor is called , /
a temperory object will be created and / destroyed before the constructor called here returns/
. Mybe a third common Initialization / function is the unique way Init(v.c_str()); } InvalidValueException(const char* pc) { Init(pc); } void Init(const char* pc) { assert(pc); if( ! pc ) pc = "Unknown Value"; msg = new char[BUFF_SIZE]; sprintf_s(msg,BUFF_SIZE, "Invalid Value :%s ", pc);
} ~InvalidValueException() { delete[] msg; } const char* what() const { return msg; } private: /// The two variable can also be decalared as not const but /
still static, / so that client code can set the parameters dynamicly according /
to actual conditions. static const int BUFF_SIZE = 150; static const int VAL_BUFF_SIZE = 20; char* msg; }; /// Base class for all data type which can be used to define a Property / default constructor is accepted , custumized constructor /
may be needed for / special data type(char* for example). template class Property { public: /// copy constructor virtual P operator=(const Property& src) { return operator=(src.value); } virtual P operator=(const P& p) { value = p; return value; } /// the following operators can just used to operate the P /
of build-in types or those types / which have defined corresponding operation virtual P operator+(const P& p) { return value+p;} virtual Property& operator+=(const P& p) { value += p; return *this; } // data convention operator P() const{ // const is necessary return value; } friend ostream& operator<< <>(ostream&s, const Property

& P); protected: P value; };

template
ostream& operator<<(ostream&s, const Property

& P) { s< Integer which is used to substitute int; class Integer :public Property { public : // overload operator= for value check if needed int operator=(const int& v) { if( v<= 0 || v>300){ // throw new InvalidValueException(v);
// cause unhandled exception throw InvalidValueException(v); } return Property::operator =(v); } }; /// A class representing a string, which can used as a Property class String: public Property { public: // overload operator= for value check if needed string operator=(const string& str) { if(str.size() <= 0) throw InvalidValueException(str); return Property::operator =(str); } // overload operator= for special data type string operator=(const char* pchar) { if(pchar == NULL) throw InvalidValueException(string("NULL")); return operator=(string(pchar)); } }; /// Student /// A concrete demo class for Property type, class Student { public: Integer Age; String Name; Student(string name, int age) { Name = name; Age = age; } friend ostream& operator<<(ostream& s, const Student& student); }; ostream& operator<<(ostream& s, const Student& student) { s<http://www.wangchao.net.cn/bbsdetail_149658.html
http://blog.youkuaiyun.com/pankun/archive/2006/02/08/594274.aspx

这两篇文章的手法基本一致,都是使用函数指针,但需要使用宏进行初始化,这和我前面写的一篇关于使用C语言模拟面向对象语言编程的文章用的方法差不多,我感觉不是特别自然,看起来还是有点儿别扭,我这里的代码感觉还是比较自然一些。但,我这里没有考虑属性是否为只读/只写的问题,倒也可以通过Template

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值