• C++的this指针


    这篇博客主要内容翻译自国外著名程序员网站:geekersforgeekers,经过作者小幅度整理,水平有限,敬请指正.

    关于this指针的粗浅认识

    (一) this指针:

    在对象的任意非static类型的成员函数被调用时候,this指针会作为一个隐藏的参数被秘密的传递给该成员函数.
    

    (二) this指针的类型:

    • 首先,this指针本身是一个const类型的指针(注意是指针是const的,不是指向的对象是const的),例如对于类X,
      那么它的this指针类型就是X * const
    #include<iostream>
    using namespace std;
     
    class Test
    {
    private:
      int x;
    public:
      Test(int x = 0) { this->x = x; }
      void change(Test *t) { this = t; } //试图赋值失败,因为this是const类型指针
      void print() { cout << "x = " << x << endl; }
    };
     
    int main()
    {
      Test obj(5);
      Test *ptr = new Test (10);
      obj.change(ptr);
      obj.print();
      return 0;
    }
    
    • 另外,this指针指向的类型根据成员函数实际的类型确定,例如X有个const类型的成员函数, 那么this指针类型就const X * const
    #include<iostream>
    class X {
       void fun() const {
        // this is passed as hidden argument to fun(). 
        // Type of this is const X* 
        }
    };
    

    (三)何时使用this指针

    • 当局部变量与类成员变量同名
    #include<iostream>
    using namespace std;
     
    /* local variable is same as a member's name */
    class Test
    {
    private:
       int x;
    public:
       void setX (int x)
       {
           // The 'this' pointer is used to retrieve the object's x
           // hidden by the local variable 'x'
           this->x = x;
       }
       void print() { cout << "x = " << x << endl; }
    };
     
    int main()
    {
       Test obj;
       int x = 20;
       obj.setX(x);
       obj.print();
       return 0;
    }
    
    • 返回调用对象的引用时候
    /* Reference to the calling object can be returned */
    Test& Test::func ()
    {
       // Some processing
       return *this;
    }
    

    (四)delete this指针

    什么?要删除this指针?对,你没有看错,就是要删出它,其实这也没什么奇怪的,需要注意的就是:
    
    • delete函数释放的只能是堆里面的内存,也就是说是new出来的空间
    • delete完this指针之后,对象的所有成员都不能再被访问

    下面代码就会体现出来:

    class A
    {
      public:
        void fun()
        {
            delete this;
        }
    };
    
    int main()
    {
      /* Following is Valid */
      A *ptr = new A;
      ptr->fun ; // 没有问题
      ptr = NULL // make ptr NULL to make sure that things are not accessed using ptr. 
    
    
      /* And following is Invalid: Undefined Behavior */
      A a;
      a.fun(); // 释放栈上的空间,会出错
    
      getchar();
      return 0;
    }
    
    
  • 相关阅读:
    InjectAPC全部项目(Win32和Win64位)
    Codeforces Round #377 (Div. 2)
    Codeforces Canada Cup 2016
    UVa 1395 (最小生成树)
    空间表SpaceList
    线程中的临界区的应用
    【题解】狼和羊-C++
    【基础算法-树状数组】入门-C++
    【题解】在你窗外闪耀的星星-C++
    【题解】[NOIP模拟题]我要的幸福-C++
  • 原文地址:https://www.cnblogs.com/sosohu/p/4156115.html
Copyright © 2020-2023  润新知