我很好奇其他人是如何使用这个关键字的。我倾向于在构造函数中使用它,但我也可能在整个类的其他方法中使用它。一些例子:

在构造函数中:

public Light(Vector v)
{
    this.dir = new Vector(v);
}

在其他地方

public void SomeMethod()
{
    Vector vec = new Vector();
    double d = (vec * vec) - (this.radius * this.radius);
}

当前回答

我只在绝对必要的时候使用它,即当另一个变量遮蔽另一个变量时。比如这里:

class Vector3
{
    float x;
    float y;
    float z;

    public Vector3(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

}

或者像Ryan Fox指出的,当你需要把它作为参数传递时。(局部变量优先于成员变量)

其他回答

这取决于我所遵循的编码标准。如果我们用_来表示一个实例变量,那么“this”就多余了。如果我们不使用_,那么我倾向于使用这个来表示实例变量。

每当我引用一个实例变量时,我都会使用它,即使我不需要。我认为这让代码更清晰。

c++中还有一种用法没有提到,那就是不引用自己的对象,也不从接收到的变量中消除成员的歧义。

您可以使用它在从其他模板继承的模板类中将非依赖名称转换为依赖参数的名称。

template <typename T>
struct base {
   void f() {}
};

template <typename T>
struct derived : public base<T>
{
   void test() {
      //f(); // [1] error
      base<T>::f(); // quite verbose if there is more than one argument, but valid
      this->f(); // f is now an argument dependent symbol
   }
}

模板是用两遍机制编译的。在第一次传递过程中,只解析和检查非参数相关的名称,而仅检查相关名称的一致性,而不实际替换模板参数。

At that step, without actually substituting the type, the compiler has almost no information of what base<T> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.

解决方法是将非相关名称f转换为相关名称。这可以通过几种方式来实现,通过显式地声明它实现的类型(base<T>::f——添加base<T>使符号依赖于T,编译器只会假设它存在,并在参数替换后推迟第二次传递的实际检查。

第二种方法,如果你从有多个参数或长名称的模板继承,那就排序得更好,就是在符号前添加一个this->。因为你实现的模板类确实依赖于一个实参(它继承自base<T>) this->是实参依赖的,并且我们得到了相同的结果:this->f在模板形参替换之后的第二轮被检查。

我在任何可能有歧义的地方都使用它(显然)。不只是编译器的模糊性(在这种情况下是必需的),还有查看代码的人的模糊性。

在Jakub Šturc的回答中,他关于在构造器之间传递数据的第5条可能需要一些解释。这是在重载构造函数中,并且是强制使用This的一种情况。在下面的例子中,我们可以使用默认形参从无参数构造函数调用参数化构造函数。

class MyClass {
    private int _x
    public MyClass() : this(5) {}
    public MyClass(int v) { _x = v;}
}

我发现有时候这是一个特别有用的功能。