C++ 使用或不使用';t使用';这';在对象内

C++ 使用或不使用';t使用';这';在对象内,c++,methods,this,member,C++,Methods,This,Member,我的问题是指当我想调用同一类的其他方法时的情况。使用“this”和不使用“this”有什么区别?类的变量也是如此。通过“this”访问这些变量有区别吗?它是否与这些方法/变量是否为私有/公共相关?例如: class A { private: int i; void print_i () { cout << i << endl; } public: void do_something () { this->print_i()

我的问题是指当我想调用同一类的其他方法时的情况。使用“this”和不使用“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;
    }
};
A类{
私人:
int i;
void print_i(){cout i=5;//与设置成员相同;
i=5;
}
};
根本没有功能上的区别。但有时您需要显式地包含
this
作为对编译器的提示;例如,如果函数名本身不明确:

class C
{
   void f() {}

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

还解释了显式使用
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
    }
};
int func();
模板
派生类:公共基
{
int f1()常量
{
return func();//调用上面的全局func。
}
int f2()常量
{
返回此->func();//调用Base的成员函数
}
};
在这种情况下,
this->
使函数的名称依赖, 这反过来又将绑定推迟到模板启动时 实例化。如果没有
this->
,函数名将为 定义模板时绑定,而不考虑 可能位于
Base
(因为在创建模板时不知道这一点)
定义的)

最常见的情况是在模板中<代码>此->使函数名与之相关。@James。同意;编辑了一点。