Accessing data members shadowed by parameters
In Java you can access variables in a class by using the keyword this
, so you don't have to figure out a new name for 开发者_运维问答the parameters in a function.
Java snippet:
private int x;
public int setX(int x) {
this.x = x;
}
Is there something similar in C++? If not, what the best practice is for naming function parameters?
If you want to access members via this
, it's a pointer, so use this->x
.
class Example {
int x;
/* ... */
public:
void setX(int x) {
this->x = x;
}
};
Oh, and in the constructor initialization list, you don't need this->
:
Example(int x) : x(x) { }
I'd consider that borderline bad style, though.
private int x;
public int setX(int newX) {
x = newX;
return x; //is this what you're trying to return?
}
In most cases, I will make a 'set' function like this void IE
public:
void setX(int newX) {
x = newX;
}
Depends on coding conventions.
From Google's C++ style guide:
void set_some_var(int var) { some_var_ = var; }
int some_other_var_;
精彩评论