C++this指针

先贴上一段代码

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指针

  1. this指针的类型:类类型* const
  2. 只能在“成员函数”的内部使用
  3. this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针。
  4. this指针是成员函数第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,不需要用户传递
  5. this指针作为参数,存在栈上
    相当于:
  void say(Alien *this)    //用户不能这样写
  {    
    cout << "I'm alien" << " I come from " << this->_home << endl;    
    cout << "I'm " << this->_age << "years old" << endl;    
  }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值