07 this指针
来源:互联网 发布:keynote软件 编辑:程序博客网 时间:2024/06/18 11:13
每个类对象内部都有一个指针变量指向自己本身,这个指针变量名为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
- 07 this指针
- this指针
- this指针
- this指针
- this指针
- this指针
- this 指针
- this指针
- this指针----
- this指针
- this 指针
- This 指针
- this指针
- This指针
- this指针
- this指针
- this 指针
- this指针
- html5 canvas 实现简单绘制折线图
- spring cloud放弃系列之--1-config
- 完美实现Python2和Python3共存
- 《Android源码设计模式解析与实战》读书笔记(四)——原型模式
- bootstrap 弹出框,提示框。
- 07 this指针
- python字符串替换的2种有效方法
- Charles抓包(iOS的http/https请求)
- emacs文件/目录比较工具
- 华为、中兴、烽火I2接口接入
- Centos搭建JavaWeb环境与部署
- 博客的开始
- Android开发SD卡文件操作工具类
- POJ 1016 Numbers That Count 笔记