1. 意义
系统在创建对象时,默认生成的指向当前对象的指针。这样作的目的,就是为了带来方便。在所有构造函数以及成员函数的隐形参数第一个就是this指针。
2. 作用
- 避免构造器的入参与成员名相同。
- 基于 this 指针的自身引用还被广泛地应用于那些支持多重串联调用的函数中。比如连续赋值。如下:
#include <iostream>
using namespace std;
class Stu
{
public:
Stu(string name, int age) // :name(name),age(age)
{
this->name = name;
this->age = age;
}
Stu & growUp()
{
this->age++;
return *this; // return this; ??
}
void display()
{
cout<<name<<" : "<<age<<endl;
}
private:
string name;
int age;
};
int main()
{
Stu s("123",20);
s.display();
s.growUp().growUp().growUp().growUp().growUp();
s.display();
return 0;
}