this指针

指向成员函数所作用的对象

class Complex {
public:
   double real, imag;
   void Print() { cout << real << "," << imag ; }
   Complex(double r,double i):real(r),imag(i){ }
    Complex AddOne() {
     this->real ++; //等价于 real ++;
      this->Print(); //等价于 Print
      return * this;
    }
}; 
int main() {
   Complex c1(1,1),c2(0,0);
   c2 = c1.AddOne();
   return 0;
} //输出 2,1

编译为C语言的话,就相当于先编译成全局函数。如下

class CCar
{
   public:
   int price;
   void SetPrice(int p);
};
void CCar::SetPrice(int p)
{ price = p; }

int main() {
  CCar car;
  car.SetPrice(20000);
  return 0;
}


struct CCar {
  int price;
};
void SetPrice
(struct CCar * this,int p)
{ this->price = p; }

int main() {
  struct CCar car;
  SetPrice( & car,20000);
  return 0;
}

思考:

class A
{
int i;
 public:
 void Hello() { cout << "hello" << endl; }
}; //void Hello(A * this ) { cout << "hello" << endl; }
int main()
{
 A * p = NULL;
 p->Hello(); //Hello(p);
} // 输出:hello

<v>虽然创建了一个没有实例对象的p指针,但是已经定义了p的类型,作为全局函数的Hello()是可以根据*p打印“hello”的,但是this.i就是错误的了</v>

静态成员函数中不能使用 this 指针,因为静态成员函数并不具体作用与某个对象

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容