Liny_@NotePad

沉迷ACG中

C++中的this指针

YOYO posted @ 2009年8月21日 00:27 in 【C/C++】 with tags this , 2131 阅读

 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. }

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter