this是一个const指针,存的是当前对象的地址,指向当前对象,经过this指针能够访问类中的全部成员。c++
当前对象是指正在使用的对象,好比a.print()
,a
就是当前对象。函数
关于thisthis
this只能在成员函数中使用,全局函数,静态函数不能使用this。由于静态函数没有固定对象。spa
#include <bits/stdc++.h> using namespace std; class A { private : int a; public : A(int x = 0) : a(x) {} void set(int x) { a = x; } void print() {printf("%d\n", a);} }; int main() { A a, b; int x; a.set(111); b.set(222); a.print(); b.print(); return 0; }
输出:指针
111
222code
能够看出赋值的时候是分别给当前对象的成员赋的值。
就像上文中提到的3同样,拿set()
函数来讲,其实编译器在编译的时候是这样的对象
void set(A *this, int x) { this->a = x; }
那何时要调用this指针呢?编译器
1. 在类的非静态成员函数中返回对象的自己时候,直接用return *this
。it
2. 传入函数的形参与成员变量名相同时编译
例如
#include <bits/stdc++.h> using namespace std; class A { private : int x; public : A() {x = 0;} void set(int x) { x = x; } void print() { printf("%d\n", x); } }; int main() { A a, b; int x; a.set(111); b.set(222); a.print(); b.print(); return 0; }
输出是
0
0
这时由于咱们的set()函数中,编译器会认为咱们把成员x的值赋给了参数x;
若是咱们改为这样,就没有问题了
#include <bits/stdc++.h> using namespace std; class A { private : int x; public : A() {x = 0;} void set(int x) { this->x = x; } void print() { printf("%d\n", x); } }; int main() { A a, b; int x; a.set(111); b.set(222); a.print(); b.print(); return 0; }
这样输出的就是
111
222
并且这段代码一目了然,左值是类成员x,右值是形参x。