类与对象之this指针


​ this指针是隐含每一个非静态成员函数内的一种指针,this指针不需要定义,直接使用即可。

this指针的用途:

  • 当形参和成员变量同名时,可用this指针来区分
  • 在类的非静态成员函数中返回对象本身,可使用return *this
  • 存放当前对象的地址

简单实例

#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
int age;
Person(int age)
{
//当形参与成员变量相同时,用this指针区别
this->age = age;
}
Person& personageAdd(Person& p)
{
this->age += p.age;
//返回对象本身
return *this;
}
};

void test01()
{
Person p1(10);
cout << "年龄是:" << p1.age << endl;
}
void test02()
{
Person p1(10);
Person p2(10);
//链式法则
p2.personageAdd(p1).personageAdd(p1).personageAdd(p1);
cout << "年龄是:" << p2.age << endl;
}
int main()
{
test01();
test02();
return 0;
}
年龄是:10
年龄是:40

课本实例

class Cdate
{
int Date_Year, Date_Month, Date_Day;
public:
void SetDate(int, int, int);
void Display();

};
void Cdate::SetDate(int y, int m, int d)
{
Date_Day = d;
Date_Month = m;
Date_Year = y;
}

void Cdate::Display()
{
cout << "调用该函数的this指针:";
cout << this << endl;
cout << "当前的对象Date_Year成员起始地址:";
cout << &this->Date_Year << endl;
cout << this->Date_Year << "-" << this->Date_Month << "-" << this->Date_Day << endl;
cout<< Date_Year << "-" << Date_Month << "-" <<Date_Day << endl;
}
int main()
{
Cdate date1;
date1.SetDate(2025, 2, 4);
cout << "date1地址" << &date1 << endl;
date1.Display();
system("pause");
return 0;
}
date1地址0000002A83F1FA48
调用该函数的this指针:0000002A83F1FA48
当前的对象Date_Year成员起始地址:0000002A83F1FA48
2025-2-4
2025-2-4

Author: T1g3r
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source T1g3r !
评论
  TOC