Getter和setter,指针或引用,以及在c ++中使用的良好语法? [英] Getter and setter, pointers or references, and good syntax to use in c++?
问题描述
我想知道一个很好的C ++ getters和setters的语法。
private:
YourClass * pMember ;
安装程序很容易我猜猜:
void Member(YourClass * value){
this-> pMember = value; //忘记删除等
}
和getter?
应该使用引用还是常量指针?
例如:
YourClass& Member(){
return * this-> pMember;
}
或
YourClass * Member()const {
return this-> member;
}
它们之间的区别是什么?
感谢,
Joe
编辑:
对不起,我将编辑我的问题...我知道有关引用和指针,我问的引用和const指针,作为getters,他们之间的区别,在我的代码,如hte future,
所以我想我会使用const指针而不是引用
常量指针不能被删除或设置,对吗?
/ p>
- 如果NULL是有效参数或返回值,请使用指针。
- 如果NULL < >
因此,如果setter应该可以用NULL调用,使用指针作为参数。否则使用引用。
如果调用包含NULL指针的对象的getter有效,它应该返回一个指针。如果这种情况是非法不变量,则返回值应该是引用。如果成员变量为NULL,getter应该抛出一个异常。
I would like to know a good syntax for C++ getters and setters.
private:
YourClass *pMember;
the setter is easy I guess:
void Member(YourClass *value){
this->pMember = value; // forget about deleting etc
}
and the getter? should I use references or const pointers?
example:
YourClass &Member(){
return *this->pMember;
}
or
YourClass *Member() const{
return this->member;
}
whats the difference between them?
Thanks,
Joe
EDIT:
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 pointers can't be delete or setted, right?
As a general law:
- If NULL is a valid parameter or return value, use pointers.
- If NULL is NOT a valid parameter or return value, use references.
So if the setter should possibly be called with NULL, use a pointer as a parameter. Otherwise use a reference.
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.
这篇关于Getter和setter,指针或引用,以及在c ++中使用的良好语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!