10人参与 • 2025-10-22 • C/C++
c++中的私有字段取值、赋值时,一般是提供get,set函数来实现,具体使用可分以下场景:
仅对该字段做单纯的取值、赋值操作,建议直接将字段定义为public;
class test
{
public:
int age;
std::string name;
int sex;
std::string intrest;
double height;
double weight;
}可将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;如加锁等,则定义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;
}以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论