先贴上一段代码
class Alien
{
public:
Alien(int age , string home)
{
_age = age;
_home = home;
}
void say()
{
cout << "I'm alien" << " I come from " << _home << endl;
cout << "I'm " << _age << "years old" << endl;
}
private:
int _age;
string _home;
};
int main()
{
Alien a1(299, "M77");
Alien a2(128, "M78");
a1.say();
a2.say();
return 0;
}
上面的代码中有a1,a2两个对象,他们都调用say(),编译器怎么知道该输出谁的信息呢
C++中通过引入this指针解决该问题,即:C++编译器给每个“成员函数“增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有成员变量的操作,都是通过该指针去访问,只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。
this指针
- this指针的类型:类类型* const
- 只能在“成员函数”的内部使用
- this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针。
- this指针是成员函数第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,不需要用户传递
- this指针作为参数,存在栈上
相当于:
void say(Alien *this) //用户不能这样写
{
cout << "I'm alien" << " I come from " << this->_home << endl;
cout << "I'm " << this->_age << "years old" << endl;
}