-
this指针:每个成员函数都有的隐含指针,存放当前对象的地址
- 是一个常量指针
- 不是对象的一部分,不会影响 sizeof(对象) 的结果
-
任何对类成员的直接访问,都可以看成是this指针的隐式使用
-
this 的显式使用
- 类成员函数中返回类对象本身
- return *this
- 参数与数据成员名相同
- this->num=num
- 前者为数据成员,后者为参数
- 类成员函数中返回类对象本身
代码实例
#include <iostream>
using namespace std;
class CDate
{
private:
int Date_Year, Date_Month, Date_Day;
public:
void SetDate(int, int, int);
void Display();
};
void CDate::SetDate(int year, int month, int day)
{
Date_Year = year;
Date_Month = month;
Date_Day = day;
}
void CDate::Display()
{
cout << "调用该函数的对象的this指针为:";
cout << this << endl;
cout << "当前对象Data_Year成员的起始地址为:";
cout << &this->Date_Year << endl;
cout << "当前对象Data_Month成员的起始地址为:";
cout << &this->Date_Month << endl;
cout << "当前对象Data_Day成员的起始地址为:";
cout << &this->Date_Day << endl;
cout << "year=" <<this->Date_Year << " month=" << this->Date_Month << " day=" << this->Date_Day << endl;
cout << endl;
}
int main()
{
CDate date1, date2;
date1.SetDate(2021, 12, 31);
date2.SetDate(2022, 1, 1);
cout <<"date1的地址为:"<< &date1 << endl;
date1.Display();
cout << "date2的地址为:"<< &date2 << endl;
date2.Display();
return 0;
}
注:这里的 &this->Date_Year 中,“->"优先级比”&“高
所以执行的操作为 >> 先指向该成员变量再取地址