C++之Set/Get使用及说明
作者:tianzhiyi1989sq
文章介绍了C++中私有字段取值和赋值的几种常用方式:若字段多且无特殊操作,可设为public;如需统一校验,可用宏定义Get/Set函数;如需独立操作则单独实现Get/Set函数
C++——get/set
C++中的私有字段取值、赋值时,一般是提供Get,Set函数来实现,具体使用可分以下场景:
1.大量私有字段,不需校验或加锁等额外操作的
仅对该字段做单纯的取值、赋值操作,建议直接将字段定义为public;
class Test
{
public:
int age;
std::string name;
int sex;
std::string intrest;
double height;
double weight;
}2.大量私有字段,需要对字段进行判空等统一操作时
可将Get、Set定义成宏函数,减少代码量(至于使用宏函数后,代码调试不便,这个问题我觉得影响不大,变量属于类对象的属性,可直接监控对象进行调试)
// 普通变量的宏定义
#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;
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
