广州尚观科技:C++基础知识: this指针

每个类对象内部都有一个指针变量指向自己本身这个指针变量名为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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值