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

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

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

12条回答
  •  孤城傲影
    2020-11-22 15:56

    If you declare a local variable in a method with the same name as an existing member, you will have to use this->var to access the class member instead of the local variable.

    #include 
    using namespace std;
    class A
    {
        public:
            int a;
    
            void f() {
                a = 4;
                int a = 5;
                cout << a << endl;
                cout << this->a << endl;
            }
    };
    
    int main()
    {
        A a;
        a.f();
    }
    

    prints:

    5
    4

提交回复
热议问题