0

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?

4

4 回答 4

4

如果你想通过 访问成员this,它是一个指针,所以使用this->x.

于 2010-02-09T21:06:54.333 回答
1
class Example {
    int x;
    /* ... */
public:
    void setX(int x) {
        this->x = x;
    }
};

哦,在构造函数初始化列表中,你不需要this->

Example(int x) : x(x) { }

不过,我会认为这种边缘糟糕的风格。

于 2010-02-09T21:08:53.243 回答
0

取决于编码约定。

来自 Google 的C++ 风格指南

void set_some_var(int var) { some_var_ = var; }
int some_other_var_;
于 2010-02-09T21:14:10.057 回答
0
private int x;

public int setX(int newX) {
  x = newX;
  return x;  //is this what you're trying to return?  
}

在大多数情况下,我会制作一个像这样的 void IE 的“设置”函数

public:
void setX(int newX) {
  x = newX;
}
于 2010-02-09T21:05:52.533 回答