#include <iostream>
using namespace std;
class Person
{
public:
// Person(int age)
// {
// age = age;
// }
//函数重载
Person(int age,int flag)
{
if (flag)
{
//this指针指向 被调用的成员函数 所属的对象
this->age = age;
}
}
int age;
void PersonAddAge(Person &p)
{
this->age += p.age;
}
//函数重载
Person& PersonAddAge(Person &p, int flag)
{
if(flag)
{
this->age += p.age;
}
return *this;
}
};
//void test01()
//{
// Person P1(18);
// cout << P1.age << endl;
//}
void test02()
{
Person P2(19,1);
cout << P2.age << endl;
}
void test03()
{
Person P3(10,1);
Person P4(10,1);
P3.PersonAddAge(P3);
//P3.PersonAddAge(P3).PersonAddAge(P3);//报错 因为返回值为void 不是对象
cout << "P3的age:" << P3.age << endl;
}
void test04()
{
Person P5(10,1);
Person P6(10,1);
P6.PersonAddAge(P5,1).PersonAddAge(P5,1).PersonAddAge(P5,1);
//*this返回了对象本身 但在函数返回值的时候需要注明
//Person类型为值类型 每次返回的对象都是拷贝构造函数复制的对象 打印出来仅有一次对该对象本身的操作
//Person& 解引用类型才是返回对象本身
cout << "P6的age:" << P6.age << endl;
}
int main()
{
// this指针的用途
// 1、当形参和成员变量同名时,可用this指针来区分
// 2、this指针不需要定义 直接使用
// 3、在类的非静态成员函数中返回对象本身 可以用 return *this (返回本体)
//test01();//返回的为Person::age的地址 证明赋值操作并不成功
test02();// success
test03();
test04();
cout << "Hello World!" << endl;
return 0;
}
C++ this指针 学习笔记
于 2023-09-17 01:05:15 首次发布