this指针

this是C++的一个关键字,本质是指向创建的对象的地址

this指针的特性:
1.this指针是const指针,它的值不能被修改。
2.只能在成员函数内部使用。
3.只有当对象被创建后 this 才有意义,因此不能在 static 成员函数中使用。

this指针的作用:
1.用来区分成员变量和形参

#include <iostream>

using namespace std;

class Demo
{
private:
    int num;
public:
    Demo(int num = 10)
    {
        // this用来区分成员变量和形参
        this->num = num;
    }
    void printNum()
    {
        cout << "num is:" << num << endl;
    }
};

int main(int argc, char *argv[])
{
    Demo demo;
    demo.printNum();
    return 1;
}

输出:
num is10

 

posted @ 2023-05-16 16:26  jason8826  阅读(5)  评论(0编辑  收藏  举报