When should I make explicit use of the `this` pointer?

后端 未结 12 1286
甜味超标
甜味超标 2020-11-22 15:19

When should I explicitly write this->member in a method of a class?

12条回答
  •  耶瑟儿~
    2020-11-22 15:37

    You only have to use this-> if you have a symbol with the same name in two potential namespaces. Take for example:

    class A {
    public:
       void setMyVar(int);
       void doStuff();
    
    private:
       int myVar;
    }
    
    void A::setMyVar(int myVar)
    {
      this->myVar = myVar;  // <- Interesting point in the code
    }
    
    void A::doStuff()
    {
      int myVar = ::calculateSomething();
      this->myVar = myVar; // <- Interesting point in the code
    }
    

    At the interesting points in the code, referring to myVar will refer to the local (parameter or variable) myVar. In order to access the class member also called myVar, you need to explicitly use "this->".

提交回复
热议问题