深度理解c++中的this指针
1.this指针,就是一个指向当前对象的指针。我们知道,定义出一个类,它在内存中是不占空间的,只有定义了该类类型的对象时,系统就会为该对象分配一段存储空间,这段空间里只存储成员变量,对于成员函数,是存放在代码区的。(复习:内存分为5大区:静态区、常量区、栈、堆、代码区)。下边给出一个日期类,通过这个实例,深度理解this指针。
#define_CRT_SECURE_NO_WARNINGS1
#include
usingnamespacestd;
classDate
{
public:
voidsetYear(intyear)
{
m_year=year;
}
voidsetMonth(intmonth)
{
m_month=month;
}
voidsetDay(intday)
{
m_day=day;
}
voidprint()
{
cout<<m_year<<"-"<<m_month<<"-"<<m_day<<endl;
}
private:
intm_year;
intm_month;
intm_day;
};
intmain()
{
Datedate;
date.setYear(2016);
date.setMonth(7);
date.setDay(4);
date.print();
system("pause");
return0;
}
2.参数里的this指针一般不需要写,系统会隐式将对象的首地址传给函数,但是如果要写,函数调用的时候也需要写上对象的地址,函数体中的this并不是在所有情况都可以省略,比如:(仍然使用上边的日期类)
voidsetYear(intm_year)
{
this->m_year=m_year;
}
在这种情况下出现了重名,函数体的this必须写,当然有一定基础的程序员才不会这么写呢。