this指针是c++中提供的特殊的对象指针,其指向的是被调用的成员函数所属的对象。
#include<iostream>
using namespace std;
class person {
public:
person(int age) {
this->age = age;//作用(1)用于区分形参和成员对象
}
int age;
//不加&,则返回的是值,那么每次返回的都不是同一个对象
person& intAddAge(person &p) {
this->age += p.age;
return *this;//作用(2)返回本身是用*this
}
};
void test02() {
person p1(10);
cout << "the age of p1 is " << p1.age << endl;
person p2(10);//链式编程思想
p2.intAddAge(p1).intAddAge(p1).intAddAge(p1);
cout << "the age of p2 is " << p2.age << endl;
}
int main() {
test02();
return 0;
}
文章介绍了C++中的this指针,它指向被调用成员函数所属的对象。在示例代码中,this指针用于区分形参和成员变量,并在intAddAge方法中实现链式编程,通过返回*this来连续调用成员函数。
463

被折叠的 条评论
为什么被折叠?



