目录
- C++——get/set
- 1.大量私有字段,不需校验或加锁等额外操作的
- 2.大量私有字段,需要对字段进行判空等统一操作时
- 3.少量私有字段,需要对字段进行独立的操作
- 总结
C++—&md编程客栈ash;get/set
C++中的私有字段取值、赋值时,一般是提供Get,Set函数来实现,具体使用可分以下场景:
1.大量私有字段,不需校验或加锁等额外操作的javascript
仅对该字段做单纯的取值、赋值操作,建议直接将字段定义为public;
class Test { public: int age; std::stjkVQWHvring name; int sex; std:http://www.devze.com:string intrest; double height; double weight; }
2.大量私有字段,需要对字段进行判空等统一操作时
可将Get、Set定义成宏函数,减少代码量(至于使用宏函python数后,代码调试不便,这个问题我觉得影响不大,变量属于类对象的属性,可直接监控对象进行调试)
// 普通变量的宏定义 #define PropertyBuilder(type, name)\ public:\ inline void Set##name(const type& para){\ m_##name = para; } inline type& Get##name(){\ return m_##name; } private:\ type m_##name; // 指针变量的宏定义 #define PointerPropertyBuilder(type, name)\ public:\ inline void Set##name(const type* para){\ // para is nullptr m_##name = para; } inline type& Get##name(){\ // IsValid return m_##name; } private:\ type* m_##name;
3.少量私有字段,需要对字段进行独立的操作
如加锁等,则定义Get/Set函数,在cpp文件中具体实现
class Test { public: void SetResource(const char* v); char* GetResource(); private: char* m_resource; } void Test::SetResource(const int v) { m_resource = v; } char* Test::GetResource() { // lock // other operation return m_resource; }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论