this指针指向被调用的成员函数所属对象
this指针的用途
1.当形参和成员变量重名时,可以用this指针来区分。
2.在类的非静态成员函数中返回对象本身,可以使用return *this;
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
//当形参和成员变量重名时,可以用this指针来区分。
//this指针指向被调用的成员函数所属对象
this->age = age;
}
Person& PersonAddPerson(Person &p)
{
this->age += p.age;
//返回对象本身
return *this;
}
int age;
};
void test01()
{
Person p1(18); //this指针指向被调用函数所属的对象,调用了构造函数Person,所属对象p1
cout << "p1的年龄:" << p1.age << endl; //18
}
void test()
{
Person p1(10);
Person p2(10);
//PersonAddPerson函数返回引用(&Person)是返回本体,若返回值(Person),则会创建新的对象,则p2的年龄输出就不是40
p2.PersonAddPerson(p1).PersonAddPerson(p1).PersonAddPerson(p1);
cout << "p2的年龄:" << p2.age << endl;
}
int main()
{
test();
system("pause");
}
结果如下
https://www.bilibili.com/video/BV1et411b73Z?p=115