每个类对象内部都有一个指针变量指向自己本身, 这个指针变量名为this,权限是private,只能在类的内部访问.
this指针可用于获取当前对象的地址.
1
2 #include<iostream>
3
4 using namespacestd;
5
6 class MyCls {
7 private :
8 string name;
9
10 public:
11 MyCls(stringname) {
12 cout <<this << endl; //输出当前对象的地址
13 }
14
15 };
16
17 int main(void)
18 {
19 MyClsa("keke");
20
21 cout <<&a << endl;
22
23 return 0;
24 }
编译执行输出:
[root@localhost07this]# ./a.out
0x7ffcd7322660
0x7ffcd7322660
也可以用于区别类对象属性成员名与参数名的冲突.
1
2 #include<iostream>
3
4 using namespacestd;
5
6 class MyCls {
7 private :
8 string name;
9
10 public:
11 MyCls(stringname) {
12 //把传进来的name赋值给类对象的属性成员name
13
14 // name= name; //局部优先的原因,这样就函数参数name等于它本身
15 this->name = name; //通过this指针指定属性成员name的值为参数name的值
16
17 //MyCls::name = name; //或者使用这种方法
18 }
19
20 voidprint_name() {
21 cout <<name << endl;
22 }
23 };
24
25 int main(void)
26 {
27 MyClsa("keke");
28
29 a.print_name();
30 return 0;
31 }
编译执行后的输出:
[root@localhost07this]# g++ 01test.cpp
[root@localhost07this]# ./a.out
keke