C++ //this 指针的使用 //1 解决名称冲突 //2 返回对象本身 用 *this
2021/8/6 22:09:22
本文主要是介绍C++ //this 指针的使用 //1 解决名称冲突 //2 返回对象本身 用 *this,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1 //this 指针的使用 2 //1 解决名称冲突 3 //2 返回对象本身 用 *this 4 5 #include <iostream> 6 #include <string> 7 using namespace std; 8 9 class Person 10 { 11 public: 12 Person(int age) 13 { 14 //this指针指向 被调用的成员函数 所属的对象 15 this->age = age; 16 } 17 Person & PersonAddAge(Person &p) 18 { 19 this->age += p.age; 20 //this指向P2的指针 而*this指向的就是P2这个对象的本体 21 return *this; 22 } 23 24 int age; 25 }; 26 //1 解决名称冲突 27 void test01() 28 { 29 Person p1(18); 30 cout << "p1的年龄为: " << p1.age << endl; 31 } 32 33 //2 返回对象本身 用 *this 34 void test02() 35 { 36 Person p1(10); 37 Person p2(10); 38 39 40 //链式编程思想 41 p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1); 42 43 cout << "02==p1的年龄为: " << p1.age << endl; 44 cout << "02==p2的年龄为: " << p2.age << endl; 45 } 46 47 int main() 48 { 49 //test01(); 50 test02(); 51 }
这篇关于C++ //this 指针的使用 //1 解决名称冲突 //2 返回对象本身 用 *this的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享