this
指针(本质:指针常量)指向被调用的成员函数所属的对象,最常用的两大功能:
- 当形参和成员变量同名时,可用
this
区分 - 返回对象本身
示例如下:
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age; // 当形参和成员变量同名时,可用 `this` 区分
}
Person& PersonAdd(int age) // 注意类型为 Person& (引用类型);如果类型为 Person 则返回的是一个新的对象
{
this->age += age;
return *this; // 返回对象本身,以便链式追加函数运算
}
int age;
};
int main()
{
Person p(10);
p.PersonAdd(1).PersonAdd(2).PersonAdd(3);
cout << p.age << endl;
}