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 }

 

posted on 2021-08-06 19:52  Bytezero!  阅读(95)  评论(0编辑  收藏  举报