#include<iostream>
using namespace std;
//this指针
class Person {
public:
Person(int age) {
//this指针指向 被调用的成员函数 所属的对象
this->age = age;
}
Person & PersonADDage(Person &p) {
this->age += p.age;
//this指向p2的指针 *this指向p2这个对象的整体
return *this;
}
int 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).PersonADDage(p1).PersonADDage(p1);
cout << "p1+p2=" << p2.age;
}
int main() {
//test01();
test02();
return 0;
}
《柳如烟的白月光回国了,于是我选择努力学c++,考上大厂》之this指针
于 2024-03-03 15:56:23 首次发布