this 指针指向被调用的成员函数所属的对象
用途一:指向名称冲突
#include <iostream>
using namespace std;
class Person
{
public:
Person (int age)
{
this->age =age;
}
int age;
};
void test01 ()
{
Person p1(18);
cout << "p1的年龄为: " << p1.age << endl;
}
int main()
{
test01();
return 0;
}
Person p1(18);调用了有参构造函数,相当于this指针指向的是被调用了的成员函数所属的对象
成员函数谁在调呢?p1在调,所以this指向的是p1,如果有p2,this指向p2,有p3,this指向p3.
谁调用有参构造,this就指向谁
用途二:
返回对象本身用*this
#include <iostream>
using namespace std;
class Person
{
public:
Person (int age)
{
this->age = age;
}
Person& PersonAddAge(Person &p)
{
this->age += p.age;
return *this;
}
int age;
};
void test02 ()
{
Person p1(10);
Person p2(20);
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
cout << "p2的年龄为: " << p2.age << endl;
}
int main()
{
test02();
return 0;
}