C++ this指针

C++ this指针教程

C++ 中,有一个 this 关键字,其是一个指针,同时也是一个 const 指针,它指向当前对象(也就是当前正在使用的对象),通过它可以访问当前对象的所有成员。

C++ this指针的本质

this 实际上是 成员函数 的一个形参,在调用成员函数时将对象的地址作为实参传递给 this。不过 this 这个形参是隐式的,它并不出现在代码中,而是在编译阶段由编译器默默地将它添加到参数列表中。

this 作为隐式形参,本质上是成员函数的局部变量,所以只能用在成员函数的内部,并且只有在通过对象调用成员函数时才给 this 赋值。

this 是 const 指针,它的值是不能被修改的,一切企图修改该指针的操作,如赋值、递增、递减等都是不允许的。

this 只能在成员函数内部使用,用在其他地方没有意义,也是非法的。只有当对象被创建后 this 才有意义,因此不能在 static 成员函数中使用。

案例

C++ this使用

C++ this使用

#include <iostream> using namespace std; class Student { public: Student(string name, int age) { this->m_name = name; this->m_age = age; } void sayHello() { cout << "I am " << this->m_name << " and i am " << this->m_age << " years old!" << endl; } private: string m_name; int m_age; }; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; Student stu("HaiCoder", 109); stu.sayHello(); return 0; }

程序运行后,控制台输出如下:

30_C this指针.png

我们可以看到,我们在 构造函数 里面,通过了 this 指针,访问了 成员变量,同时,我们在成员函数 sayHello 里面,一样通过 this 指针访问了成员变量。

C++ this指向的值

C++ this指向的值

#include <iostream> using namespace std; class Student { public: Student(string name, int age) { this->m_name = name; this->m_age = age; } void show() { cout << "this = " << this << endl; } private: string m_name; int m_age; }; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; Student stu("HaiCoder", 109); stu.show(); cout << "stu = " << &stu << endl; Student stu1("HaiCoder", 109); stu1.show(); cout << "stu1 = " << &stu1 << endl; return 0; }

程序运行后,控制台输出如下:

31_C this指针指向的值.png

我们在成员函数 show 里面,打印了 this 指针的值,同时,我们在 main 函数里面,打印了对象的地址,我们发现,同一个对象的 this 的值和其地址是相同的。

因此,可以说,this 就是对象本身。

C++ this指针教程

在 C++ 中,有一个 this 关键字,其是一个指针,同时也是一个 const 指针,它指向当前对象(也就是当前正在使用的对象),通过它可以访问当前对象的所有成员。

this 实际上是成员函数的一个形参,在调用成员函数时将对象的地址作为实参传递给 this。不过 this 这个形参是隐式的,它并不出现在代码中,而是在编译阶段由编译器默默地将它添加到参数列表中。