this指针存在于类的成员函数中,指向被调用函数所在的类实例的地址。

  根据以下程序来说明this指针  

  1. #include<iostream.h>  
  2. class Point   
  3. {   
  4. private:    
  5.     int x, y;    
  6. public:    
  7.     Point(int a, int b) 
  8.     { 
  9.          x=a; 
  10.          y=b; 
  11.      }    
  12.  
  13.      void MovePoint( int a, int b) 
  14.      { 
  15.           x+=a; 
  16.           y+=b; 
  17.       }    
  18.  
  19.      void print() 
  20.     { 
  21.           cout<<"x="<<x<<"y="<<y<<endl; 
  22.      }    
  23. };     
  24.  
  25. void main( )   
  26. {  
  27.     Point point1( 10,10);   
  28.     point1.MovePoint(2,2); 
  29.     point1.print( );  
  30. }  

    当对象point1调用MovePoint(2,2)函数时,即将point1对象的地址传递给了this指针。   MovePoint函数的原型应该是 void MovePoint( Point *this, int a, int b);第一个参数是指向该类对象的一个指针,我们在定义成员函数时没看见是因为这个参数在类中是隐含的。这样point1的地址传递给了this,所以在 MovePoint函数中便显式的写成:

  1. void MovePoint(int a, int b) { this->x +=a; this-> y+= b;}  

  即可以知道,point1调用该函数后,也就是point1的数据成员被调用并更新了值。