Getter 和 setter、指针或引用以及在 C++ 中使用的良好语法?

2022-01-05 00:00:00 reference pointers c++ getter setter

我想知道 C++ getter 和 setter 的良好语法.

I would like to know a good syntax for C++ getters and setters.

private:
YourClass *pMember;

我猜二传手很容易:

void Member(YourClass *value){
  this->pMember = value; // forget about deleting etc
}

和吸气剂?我应该使用引用还是常量指针?

and the getter? should I use references or const pointers?

示例:

YourClass &Member(){
   return *this->pMember;
}

YourClass *Member() const{
  return this->member;
}

它们之间有什么区别?

谢谢,

对不起,我会编辑我的问题...我知道引用和指针,我问的是引用和常量指针,作为吸气剂,它们在我的代码中的区别是什么,比如在未来,应该怎么做如果我走一段路,我预计会输......

sorry, I will edit my question... I know about references and pointers, I was asking about references and const pointers, as getters, what would be the difference between them in my code, like in hte future, what shoud I expect to lose if I go a way or another...

所以我想我会使用常量指针而不是引用

so I guess I will use const pointers instead of references

const 指针不能被删除或设置,对吧?

const pointers can't be delete or setted, right?

推荐答案

作为一般规律:

  • 如果 NULL 是有效参数或返回值,请使用指针.
  • 如果 NULL NOT 是有效的参数或返回值,请使用引用.
  • If NULL is a valid parameter or return value, use pointers.
  • If NULL is NOT a valid parameter or return value, use references.

因此,如果可能应该使用 NULL 调用 setter,请使用指针作为参数.否则使用参考.

So if the setter should possibly be called with NULL, use a pointer as a parameter. Otherwise use a reference.

如果调用包含 NULL 指针的对象的 getter 是有效的,它应该返回一个指针.如果这种情况是非法的不变量,则返回值应该是引用.如果成员变量为 NULL,则 getter 应该抛出异常.

If it's valid to call the getter of a object containing a NULL pointer, it should return a pointer. If such a case is an illegal invariant, the return value should be a reference. The getter then should throw a exception, if the member variable is NULL.

相关文章