‘this’ pointer in C++

this指針作爲一個隱藏的參數傳遞給所有的non-static成員函數,作爲一個局部變量。是一個const-pointer,指向的是當前對象的地址。在static成員函數中沒有this指針,因爲static成員變量不能調用對象內的non-static成員。

this指針有兩個用途:

(1)返回調用對象的引用。

/* Reference to the calling object can be returned */
Test& Test::func ()
{
   // Some processing
   return *this;
} 


(2)當局部變量名稱和成員變量名稱相同時。

#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;
}

this指針的類型

當類X的成員函數聲明爲const時,this指針爲:const  X*
當類X的成員函數聲明爲volatile時,this指針爲:volatile X*
當類X的成員函數聲明爲const volatile時,this指針爲:const  volatile X*
#include<iostream>
class X {
   void fun() const {
    // this is passed as hidden argument to fun(). 
    // Type of this is const X* 
    }
};
Run on IDE
Code 2

#include<iostream>
class X {
   void fun() volatile {
     // this is passed as hidden argument to fun(). 
     // Type of this is volatile X* 
    }
};
Run on IDE
Code 3

#include<iostream>
class X {
   void fun() const volatile {
     // this is passed as hidden argument to fun(). 
     // Type of this is const volatile X* 
    }
};

翻譯:http://www.geeksforgeeks.org/g-fact-77/

可不可以delete this指針?

可以,但只有當對象是用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;
}




發佈了68 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章