zoukankan      html  css  js  c++  java
  • win32

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

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

    #include<iostream.h>
    class Point
    { 
      int x, y;
     public:
       Point(int a, int b) { x=a; y=b;}
       void MovePoint( int a, int b){ x+=a; y+=b;}
       void print(){ cout<<"x="<<x<<"y="<<y<<endl;}
    };
    void main( )
    {
       Point point1( 10,10);
       point1.MovePoint(2,2);
       point1.print( );
    }

    当对象point1调用MovePoint(2,2)函数时,即将point1对象的地址传递给了this指针。

    MovePoint函数的原型应该是

    void MovePoint( Point *this, int a, int b);

    第一个参数是指向该类对象的一个指针,我们在定义成员函数时没看见是因为这个参数在类中是隐含的。这样point1的地址传递给了this,所以在MovePoint函数中便显式的写成:

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

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

    point1.x+= a; point1. y + = b;

    this指针变量记录的是当前对象的内存地址,即this指针指向当前的对象

  • 相关阅读:
    poj 1080 dp
    Codeforces Round #280 (Div. 2)
    Codeforces Round #279 (Div. 2)f
    Codeforces Round #278 (Div. 1)
    Codeforces Round #276 (Div. 1)
    搜索
    debug 心得
    ZOJ 1633
    DRF 一对多序列化与反序列化
    HTTP协议
  • 原文地址:https://www.cnblogs.com/strive-sun/p/14148642.html
Copyright © 2011-2022 走看看