问题引入
日期类
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 a;
};
int main()
{
Date d1, d2;
d1.Init(2022, 1, 11);
d2.Init(2022, 1, 12);
d1.Print();
d2.Print();
return 0;
}
问题:
Date
类中有
Init
与
Print
两个成员函数,函数体中没有关于不同对象的区分,那当
d1
调用
Init
函数时,该函
数是如何知道应该设置
d1
对象,而不是设置
d2
对象呢?
原因:
C++
中通过引入
this
指针解决该问题,即:
C++
编译器给每个
“
非静态的成员函数
“
增加了一个隐藏的指针参
数,让该指针指向当前对象
(
函数运行时调用该函数的对象
)
,在函数体中所有
“
成员变量
”
的操作,都是通过该
指针去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成
。
1.this指针的特性
1.
this
指针的类型:类类型
* const
,即成员函数中,不能给
this
指针赋值。
2.
只能在
“
成员函数
”
的内部使用
3.
this
指针本质上是
“
成员函数
”
的形参
,当对象调用成员函数时,将对象地址作为实参传递给
this
形参。
所以
对象中不存储
this
指针
。
4.
this
指针是
“
成员函数
”
第一个隐含的指针形参,一般情况由编译器通过
ecx
寄存器自动传递,不需要用
户传递
2.this指针存在哪里?
this指针作为形参存储在栈区的寄存器中
3. this指针可以为空吗?
可以
例如
class A
{
public:
void Print()
{
cout << "Print()" << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->Print();
return 0;
}
//正常运行
class A
{
public:
void PrintA()
{
cout << _a << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->PrintA();
return 0;
}
//运行崩溃
只要成员函数不解引用this指针 this指针可以传空