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

在构造函数中:

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 AABB
{
  // ... members
  bool intersects( AABB other )
  {
    return other.left() < this->right() &&
           this->left() < other.right() &&

           // +y increases going down
           other.top() < this->bottom() &&
           this->top() < other.bottom() ;
  }
} ;

(vs)

class AABB
{
  bool intersects( AABB other )
  {
    return other.left() < right() &&
           left() < other.right() &&

           // +y increases going down
           other.top() < bottom() &&
           top() < other.bottom() ;
  }
} ;

AABB的right()指的是哪一个?这增加了一点澄清。

我基本上只在从同一类型中引用一个类型属性时使用这个。正如另一个用户提到的,我还强调了本地字段,这样它们就不需要这样做了。

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

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指出的,当你需要把它作为参数传递时。(局部变量优先于成员变量)

黑C + +铝

它被用在赋值操作符中,大多数时候你必须检查和防止奇怪的(无意的,危险的,或只是浪费程序时间的)事情,比如:

A a;
a = a;

你的赋值操作符将被写成:

A& A::operator=(const A& a) {
    if (this == &a) return *this;

    // we know both sides of the = operator are different, do something...

    return *this;
}

我用它来调用智能感知就像JohnMcG,但我会回去擦除“this->”当我完成。我遵循微软的惯例,在成员变量前加上“m_”,所以把它作为文档是多余的。