C++this指针的用途

2022/7/30 1:26:29

本文主要是介绍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;
}


这篇关于C++this指针的用途的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程