【问题标题】:Use or don't use 'this' within a object [duplicate]在对象中使用或不使用“this”[重复]
【发布时间】:2014-06-27 14:21:09
【问题描述】:

我的问题是指我想调用同一类的其他方法的情况。使用和不使用“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;
    }
};

【问题讨论】:

    标签: c++ methods this member


    【解决方案1】:

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

    在某些情况下会有所不同:

    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-&gt; 使函数的名称依赖, 这反过来又将绑定推迟到模板何时 实例化。如果没有this-&gt;,函数名称将为 定义模板时绑定,不考虑什么 可能在Base 中(因为不知道模板何时 定义)。

    【讨论】:

      【解决方案2】:

      根本没有功能区别。但有时您需要显式包含this 作为对编译器的提示;例如,如果函数名称本身不明确:

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

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

      【讨论】:

      • 最重要的情况是在模板中。 this-&gt; 呈现函数名称依赖。
      • @詹姆斯。同意;稍微修改了一下。
      猜你喜欢
      • 2013-10-16
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 2023-03-03
      相关资源
      最近更新 更多