C++this指针的用途

this指针指向被调用的成员函数所属的对象。

this指针是隐含在每一个非静态成员函数内的一种指针。

this指针不需要定义,直接使用。

this指针的用途:

  1.当形参和成员变量同名时,可用this指针来区分(最好在命名时避免)。

  2.在类的非静态成员函数中返回对象本身,可使用return *this。

#include<iostream>
using namespace std;
class WLM
{
public:
    WLM(int age)
    {
        this->age = age;
    }

    WLM& AddAge(WLM &wlm)
    {
        this->age += wlm.age;
        return *this;
    }

    int age;
};

//1.解决名称冲突
void test1()
{
    WLM wlm1(22);
    cout << wlm1.age << endl;
}

//2.返回对象本身用*this
void test2()
{
    WLM wlm2(22);
    WLM wlm3(22);
    wlm3.AddAge(wlm2).AddAge(wlm2).AddAge(wlm2);
    cout << wlm3.age << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    //test1();
    test2();
    
    system("pause");
    return 0;
}
posted @ 2022-07-29 11:59  萌萌的保镖  阅读(124)  评论(0)    收藏  举报