【c++】this指针用途


#include using namespace std;
class Person{     public:         Person(int age){             this->age = age; //this指针指向 被调用成员函数 所属的对象,this指向p1 p2 p3.。。         }
        Person PersonAddAge(Person &p){             this->age += age;
            //this指向p2的指针,而*this指向的就是p2这个对象本身             return *this;         }         int age; //此处age和 this->age 是同一个 };
// 1、解决名称冲突 void test01(){     Person p1(18);     cout << "p1的年龄为: " << p1.age << endl; }
// 2、返回对象本身用*this void test02(){     Person p1(10);
    Person p2(10);
    //p2.PersonAddAge(p1);//函数调用一次返回类型是Person     p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);//此处链式调用是会生成p2` p2`` p2```,而最后调用的是p2.age,而不是p2`.age
    cout << "p2的年龄为: " << p2.age << endl;//最后输出的是p2.age 所以值为20 } int main() {     test02();     system("pause");     return 0; }
cpp