常见两种用法
- 01 解决名词冲突
- 返回对象本身用 *this
#include<iostream>
using namespace std;
class Person {
//private:
// int age;
public:
Person(int age) {
//this指针指向的是谁呢 被调用成员函数 所属的对象
//当形参和成员变量同名时,可以this指针来区分
this->age = age; //this指向p1
}
/*void PersonAddAge(Person& p) {
this->age += p.age;
}*/
//同理一定要引用,
Person& PersonAddAge(Person& p) {
this->age += p.age;
return *this; // this指向p2的指针,而*this指向的是p2这个对象本体
}
int age;
};
//01 解决名词冲突
void test01() {
Person p1(18);
cout << "p1的年龄" << p1.age << endl;
}
//2 返回对象本身用 *this
void test02() {
Person p1(10);
Person p2(10);
//链式编程思想 同理cout输出时候可以有多个<<
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
cout << "p2的年龄为:" << p2.age << endl;
}
int main()
{
//test01();
test02();
return 0;
}