在对象中使用或不使用'this'

Use or don't use 'this' within a object

本文关键字:this 对象      更新时间:2023-10-16

我的问题是指当我想调用同一类的其他方法时的情况。用和不用"this"有什么区别?类的变量也是如此。通过"this"访问这些变量有区别吗?是否与这些方法/变量是私有的/公共的有关?例子:

class A {
private:
    int i;
    void print_i () { cout << i << endl; }
public:
    void do_something () {
        this->print_i();    //call with 'this', or ...
        print_i();          //... call without 'this'
        this->i = 5;        //same with setting the member;
        i = 5;
    }
};

一般来说,这是一个风格问题。所有我去过的地方工作人员不喜欢使用this->,除非当必要的。

在某些情况下,它是有区别的:

int func();
template <typename Base>
class Derived : public Base
{
    int f1() const
    {
        return func();      //  calls the global func, above.
    }
    int f2() const
    {
        return this->func();  //  calls a member function of Base
    }
};

在这种情况下,this->使函数的名称依赖,这反过来又将绑定延迟到模板是什么时候实例化。如果没有this->,则函数名为在模板定义时绑定,而不考虑什么可能是在Base(因为不知道模板是什么时候)定义)。

根本没有功能差异。但有时你需要显式地包含this作为对编译器的提示;例如,如果函数名本身有歧义:

class C
{
   void f() {}
   void g()
   {
      int f = 3;
      this->f(); // "this" is needed here to disambiguate
   }
};

James Kanze的回答还解释了一种情况,即显式使用this会改变编译器选择重载名称的版本。