C/C++教程

C++ //this 指针的使用 //1 解决名称冲突 //2 返回对象本身 用 *this

本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!