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;
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论