引入
首先定义一个Date类,观察下面代码
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
//this = nullptr;
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
d1.Init(2023, 3, 19);
Date d2;
d2.Init(2004, 2, 18);
d1.Print();
d2.Print();
}
根据输出结果,可以看出
Date类含有两个成员函数Init, Print
,当d1,d2调用Init和Print后,函数可以正确进行d1,d2对象的打印,那么函数是怎么设置正确对象的
实则就是C++的this指针
特性
- this指针的类型:类类型
*const
,即成员函数中,不能给this指针赋值。 - 只能在成员函数的内部使用
- this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针
- this指针是“成员函数”第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传
递,不需要用户传递
对于先前代码,实际传参为
void Init(Date* const this, int year, int month, int day)
传入了一个Date类this指针,当d1,d2进行函数调用时,实际为
d1.Init(&d1, 2023, 3, 19);
d2.Init(&d2, 2004, 2, 18);
因为this指针是隐藏的,下述代码 (1和2,3和4) 在使用上没有区别,但通常我们并不显式的写出this指针
class Date
{
public:
//实则传入有this,隐藏了
//void Init(Date* const this, int year, int month, int day)
void Init(int year, int month, int day)
{
//1.
_year = year;
_month = month;
_day = day;
//2.
this->_year = year;
this->_month = month;
this->_day = day;
}
//c++隐藏了this指针
/*void Print(Date* const this)*/
void Print()
{
//this = nullptr;
//3.
cout << _year << "-" << _month << "-" << _day << endl;
//4.
cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
}
private:
int _year;
int _month;
int _day;
};
拓展问题
this指针存在哪里
由上述代码可以得到,编译器在生成程序时加入了获取对象首地址的相关代码
d1.Init(&d1, 2023, 3, 19)
,一般由寄存器将首地址放到 寄存器ecx中,相当于成员函数的 其他参数存放在栈中,而this指针存放在寄存器中中。
this指针可以为空吗
可以为空,当调用函数且函数内部并不适用this时 (比如仅仅执行打印/函数内部为空) ,相对如果调用函数需要使用到this则不能为空。