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

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

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

12条回答
  •  猫巷女王i
    2020-11-22 15:53

    The main (or I can say, the only) purpose of this pointer is that it points to the object used to invoke a member function.

    Base on this purpose, we can have some cases that only using this pointer can solve the problem.

    For example, we have to return the invoking object in a member function with argument is an same class object:

    class human {
    
    ... 
    
    human & human::compare(human & h){
        if (condition)
            return h;       // argument object
        else 
            return *this;   // invoking object
        }
    };
    

提交回复
热议问题