c++,const类型对象无法修改状态
c++,const类型对象无法修改状态
·
背景:Person对象
const getParent() const {return m_parent}
void clearChild() {m_children.clear()}
有一对象person,我调用getParent()方法,这个getParent()方法返回的是const类型的 person对象。此时我获取这个对象,调用clearChid()方法,这个方法是void 。无法调用。
因为返回的对象是常量类型的,无法修改状态。
解决措施1:m_children不是常量类型,改成如下(不建议,谨慎使用,其他函数可能相应要修改)
void clearChild() cosnt {m_children.clear()}
解决措施2:m_children是常量类型,改成如下(个人还是比较喜欢的,也不影响其他人写的业务)
再写一个方法getParentToClearChild()
const getParent() const {return m_parent}
getParentToClearChild() {return m_parent}
void clearChild() {m_children.clear()}
更多推荐
所有评论(0)