一.this指针介绍
class Date
{
……
}
int main()
{
Date d1,d2;
……
}
- C++编译器给每个“非静态的成员函数“增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有“成员变量”的操作,都是通过该指针去访问。
- 只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。
class Date
{
public:
/*void Init(Date* const this, int year, int month, int day)
{
this->_year = year;//编译器默认会加上this->
this->_month = month;
this->_day = day;
}
void Print(Date* const this)
{
cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
}*/
// 实参和形参位置不能显示传递和接收this指针
// 但是可以在成员函数内部使用this指针
void Init(int year, int month, int day)
{
//this = nullptr;
cout << this << endl;
this->_year = year;
this->_month = month;
this->_day = day;
}
二.this指针的特性
- this指针的类型:类的类型* const,即成员函数中,不能给this指针赋值。
- 只能在“成员函数”的内部使用
- this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针。
- this指针是“成员函数”第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,不需要用户传递
三. this指针相关面试题
1. this指针存在哪里?( 堆 栈 静态区 常量区 )
- this指针存在栈里,因为他是一个形参
- 但this指针未必存在栈里,比如在vs下它可能会用寄存器去优化(vs下面传递this指针,是通过ecx寄存器传递的,这样this访问变量提高效率)
- (this指针是对象的地址,不能说存在对象里 )
2. this指针可以为空吗?
// 1.下面程序编译运行结果是? A、编译报错 B、运行崩溃 C、正常运行
class A
{
public:
void Print()
{
cout << this << endl;
cout << "Print()" << endl; //C、正常运行
}
private:
int _a
};
int main()
{
A* p = nullptr;
p->Print(); //指针虽然调用函数,但它不会到指针指向的对象里面去找,因为它没有解引用这个指针,这个函数在公共代码区,在编译链接的阶段就知道它的代码地址了,而后就call这个地址了
//若是对象调用,则把对象取地址传入函数 -->d1.Print(&d1)
//若是指针调用,则把指针p传过去给this -->p->Print();
//this是个空指针,空指针不解引用不会有问题,故程序正常运行
return 0;
}
// 2.下面程序编译运行结果是? A、编译报错 B、运行崩溃 C、正常运行
class A
{
public:
void PrintA()
{
cout << this << endl;
cout << _a<<endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->PrintA(); //B、运行崩溃
//这两个在调用函数时,都没有解引用p,都是直接确认地址
//不同在,此处p传给this后,并对this进行访问使用,就出现了空指针问题
return 0;
}
祝大家学习愉快 : )