this指针
this指针的引出
首先我们来看一下下面这段简单的代码:
#include<iostream>
using namespace std;
class person_age
{
public:
void getage()
{
cin >> age;
}
void showage()
{
cout << "age=" << age << endl;
}
private:
int age;
};
int main()
{
person_age a;
person_age b;
a.getage();
a.showage();
b.getage();
b.showage();
return 0;
}
我们定义了一个类,当我们用这个类去实例化出两个对象,也就是实例化出a和b,之后我们进行了getage和showage操作,函数体内并没有关于类的区分,而且我们也知道类中函数代码块是共享的,那当a调用getage函数时,怎么知道是a在调用它而不是b呢?这个问题相当的重要。
C++中通过引入this指针来解决这个问题。C++编译器给每个“非静态的成员函数”增加了一个隐藏的指针参数,让该指针指向当前对象,在函数体中所有成员变量的操作,都是通过该指针去访问,只不过所有操作对用户都是不可见的,用户自己不需要传递指针参数,都是编译器自动完成。
this指针的特性
- this指针的类型:类类型* const
- 只是在成员函数内部存在使用
- this指针本质上是成员函数的一个形参,当对象调用成员函数时,将对象的地址作为实参将传递给这个形参,所以对象中并不存储this指针。
- this指针是成员函数第一个隐含的指针形参,一般情况下由编译器通过ecx寄存器自动传递,不需要用户传递。
this指针的样子
void showage()
{
cout << "age=" << age << endl;
}
void showage(person_age* this)
{
cout << "age=" << this->age << endl;
}
下面的showage被我显式的展示出了this指针。
this指针能空吗
#include<iostream>
using namespace std;
class person_age
{
public:
void getage()
{
cin >> age;
}
void showage()
{
cout << "age=" << age << endl;
}
private:
int age;
};
int main()
{
person_age* p = NULL;
p->getage();
p->showage();
return 0;
}
我们定义了该类的指针,用该指针去调用类的函数,编译可以通过,但是运行会崩溃,函数不能正常使用,由此可见,this指针也不能为空,它应当指向当前对象。