在Java中,您可以使用关键字this
访问类中的变量,因此您不必为函数中的参数找出新名称。
Java片段:
private int x;
public int setX(int x) {
this.x = x;
}
C ++中有类似的东西吗?如果没有,命名函数参数的最佳做法是什么?
答案 0 :(得分:4)
如果您想通过this
访问成员,则它是指针,因此请使用this->x
。
答案 1 :(得分:1)
class Example {
int x;
/* ... */
public:
void setX(int x) {
this->x = x;
}
};
哦,在构造函数初始化列表中,您不需要this->
:
Example(int x) : x(x) { }
但我认为这种边缘不好的风格。
答案 2 :(得分:0)
private int x;
public int setX(int newX) {
x = newX;
return x; //is this what you're trying to return?
}
在大多数情况下,我会制作一个'set'函数,就像这个void IE
public:
void setX(int newX) {
x = newX;
}
答案 3 :(得分:0)
取决于编码惯例。
来自Google的C++ style guide:
void set_some_var(int var) { some_var_ = var; }
int some_other_var_;