一、this指针的引入
C++编译器给每个“非静态的成员函数”增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有成员变量的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要传递,编译器自动完成。
先来定义一个日期类
#include<iostream>
using namespace std;
class Date
{
public:
void SetDateInfo(int year,int month,int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2;
d1.SetDateInfo(2021, 7, 26);
d2.SetDateInfo(2021, 8, 26);
d1.Print();
d2.Print();
return 0;
}
以上代码定义了两个日期类d1,d2,编译器如何知道设置的数据是d1,还是d2的?
其实存在着这个指针–>this指针(隐藏起来了)
针对上述代码:this等价于Date* const
如d1.SetDateInfo(2021,7,26)就等价于Date::SetDateInfo(&d1,2021,7,26)
又如
二、this指针的特性
1.this指针的类型:类类型* const
2.只能在“成员函数”的内部使用
3.this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参,所以对象中不存储this指针。
4.this指针时成员函数第一个隐藏的指针形参,一般情况由编译器ecx寄存器自动传递,不需要用户传递。
面试题
1.this指针存在哪里
#include<iostream>
using namespace std;
class Date
{
public:
void SetDateInfo(int year,int month,int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
Date* const& rthis = this;
cout << &rthis << endl;
cout << this << endl;
//cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
d1.Print();
return 0;
}
画图如下
所以this指针在栈上
2.this指针可以为空吗
class A
{
public:
void PrintA()
{
cout << _a << endl;
}
void Show()
{
cout << "Show()" << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->PrintA();
p->Show();
}
看看编译的过程吧
编译可以通过,但是在访问变量的时候会崩溃
因为之前说到cout<<_a<<endl==cout<< this->_a<<endl,所以在访问时会崩溃