1、指针永远指向当前对象;
2、解决命名上的冲突;
3、*this指向对象本体。
4、非静态的成员函数才有this指针。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age; //this可以解决命名冲突
}
//对比年龄
void compareAge(Person & p)
{
if (this->age == p.age) //此处可以不写this
{
cout << "年龄相等" << endl;
}
else
{
cout << "年龄不等" << endl;
}
}
//年龄相加
/*void PlusAge(Person p)
{
this->age += p.age;
}*/
//年龄相加
Person & PlusAge(Person p)
{
this->age += p.age;
return *this; //*this指向对象本体
}
int age;
};
void test01()
{
Person p1(10);
cout << "p1的年龄" << p1.age << endl;
Person p2(10);
p1.compareAge(p2);
p1.PlusAge(p2);
cout << "p1的年龄是" << p1.age << "岁" << endl;
p1.PlusAge(p2).PlusAge(p2); //返回引用的时候可以作为左值,链式编程
}
int main(void)
{
test01();
system("pause");
return EXIT_SUCCESS;
}