首先,我们先来看一个Date类:
#include <iostream>
using namespace std;
class Date
{
public:
void Init(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;
d1.Init(2020, 6, 29);
d1.Print();
Date d2;
d2.Init(2020, 6, 29);
d2.Print();
return 0;
}
对于上述类,有这样一个问题:
Date类中有 Init 与 Print 两个成员函数,函数体中没有关于不同对象的区分,那当 d1 调用 Init 函数时,该函数是如何知道应该设置 d1 对象,而不是设置 d2 对象呢?
C++中通过引入 this 指针解决该问题,即:C++编译器给每个“非静态的成员函数“增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有成员变量的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。
C++中的成员函数参数中不允许显式的写 this 指针,只能在成员函数的内部使用
this 指针的类型:类类型* const
#include <iostream>
using namespace std;
class Date
{
public:
//void Init(Date* this, int year, int month, int day);
void Init(int year, int month, int day)
{
//this->_year = year;
//this->_month = month;
//this->_day = day;
_year = year;
_month = month;
_day = day;
}
//void Print(Date* this);
void Print()
{
//cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
d1.Init(2020, 6, 29); //d1.Init(&d1, 2020, 6, 4);
d1.Print(); //d1.Print(&d1);
Date d2;
d2.Init(2020, 6, 29); //d2.Init(&d2, 2020, 6, 4);
d2.Print(); //d2.Print(&d2);
return 0;
}
小问题:
- this指针存在哪里?也就是存在进程地址空间的哪个区域?
存在栈上,因为它是一个形参。(VS下存在ecx寄存器里来传递) - this指针可以为空吗?
可以为空,在调用函数的时候,如果函数内部没有使用到this指针去访问成员变量;如果函数内部需要用到this指针去访问成员变量,则不能为空。