#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
//当形参和成员变量同名时,用this指针来区分,this指针指向成员变量
this -> age = age;
}
//void PersonAddAge(Person p)
//{
// this->age += p.age;
//}
//int age;
//用this指针返回自身
Person& PersonAddAge(Person p) //关于我的误区,引用只是别名,不是指针,返回的值就是Person类的对象,this为指针,*this就是一个对象
{
this->age += p.age;
return *this;
}
int age;
};
void test01()
{
Person p(10);
cout << p.age << endl;
}
void test02()
{
Person p1(10);
Person p2(10);
p2.PersonAddAge(p1);//想把p1的年龄加到自己身上
cout <<"PersonAddAge的一次调用" << p2.age << endl;
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);//连续加三次在自己身上
cout << "PersonAddage的连续调用" << p2.age << endl;
}
int main()
{
test02();
/*test01();*/
}
C++中的this指针笔记
最新推荐文章于 2024-05-06 22:29:10 发布