C++中的this指针

this总是指向当前对象,每次执行成员函数时,形如本例中的SetColor(int _color),总是会被编译成SetColor(CTestThis* this, int _color),编译器会自动带入对象地址作为this指针所指向的地址,本例中的全局函数也许可以加深对this指针的理解。

  1. #include <iostream>
  2.  
  3. class CTestThis
  4. {
  5. public:
  6.         int GetColor ( ) { return this->color; }
  7.         void SetColor ( int _color ) { this->color = _color; }
  8.         void Display ( ) { std:: cout << this->color << std:: endl; }
  9.  
  10. private:
  11.         int color;
  12. };
  13.  
  14. void SetColor ( int _color, CTestThis* _ )
  15. {
  16.         _->SetColor (_color );
  17. }
  18.  
  19. void Display (CTestThis* _ )
  20. {
  21.         std:: cout << _->GetColor ( ) << std:: endl;
  22. }
  23.  
  24. void main ( void )
  25. {
  26.         CTestThis test;
  27.  
  28.         test. SetColor ( 3 );
  29.         test. Display ( );
  30.  
  31.         SetColor ( 33, &test );
  32.         Display (&test );
  33.  
  34.         system ( "pause" );
  35. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值