欧美日韩不卡一区二区三区,www.蜜臀.com,高清国产一区二区三区四区五区,欧美日韩三级视频,欧美性综合,精品国产91久久久久久,99a精品视频在线观看

C語言

C++ this指針詳解

時(shí)間:2025-06-02 17:33:01 C語言 我要投稿
  • 相關(guān)推薦

C++ this指針詳解

  this 是 C++ 中的一個(gè)關(guān)鍵字,也是一個(gè) const 指針,它指向當(dāng)前對象,通過它可以訪問當(dāng)前對象的所有成員。下面是小編為大家整理的C++ this指針詳解,歡迎參考~

  所謂當(dāng)前對象,是指正在使用的對象。例如對于stu.show();,stu 就是當(dāng)前對象,this 就指向 stu。

  下面是使用 this 的一個(gè)完整示例:

  #include

  using namespace std;

  class Student{

  public:

  void setname(char *name);

  void setage(int age);

  void setscore(float score);

  void show();

  private:

  char *name;

  int age;

  float score;

  };

  void Student::setname(char *name){

  this->name = name;

  }

  void Student::setage(int age){

  this->age = age;

  }

  void Student::setscore(float score){

  this->score = score;

  }

  void Student::show(){

  cout<name<<"的年齡是"<age<<",成績是"<score<<endl;

  }

  int main(){

  Student *pstu = new Student;

  pstu -> setname("李華");

  pstu -> setage(16);

  pstu -> setscore(96.5);

  pstu -> show();

  return 0;

  }

  運(yùn)行結(jié)果:

  李華的年齡是16,成績是96.5

  this 只能用在類的內(nèi)部,通過 this 可以訪問類的所有成員,包括 private、protected、public 屬性的。

  本例中成員函數(shù)的參數(shù)和成員變量重名,只能通過 this 區(qū)分。以成員函數(shù)setname(char *name)為例,它的形參是name,和成員變量name重名,如果寫作name = name;這樣的語句,就是給形參name賦值,而不是給成員變量name賦值。而寫作this -> name = name;后,=左邊的name就是成員變量,右邊的name就是形參,一目了然。

  注意,this 是一個(gè)指針,要用->來訪問成員變量或成員函數(shù)。

  this 雖然用在類的內(nèi)部,但是只有在對象被創(chuàng)建以后才會(huì)給 this 賦值,并且這個(gè)賦值的過程是編譯器自動(dòng)完成的,不需要用戶干預(yù),用戶也不能顯式地給 this 賦值。本例中,this 的值和 pstu 的值是相同的。

  我們不妨來證明一下,給 Student 類添加一個(gè)成員函數(shù)printThis(),專門用來輸出 this 的值,如下所示:

  void Student::printThis(){

  cout<<this<<endl;

  }

  然后在 main() 函數(shù)中創(chuàng)建對象并調(diào)用 printThis():

  Student *pstu1 = new Student;

  pstu1 -> printThis();

  cout<<pstu1<<endl;

  Student *pstu2 = new Student;

  pstu2 -> printThis();

  cout<<pstu2<<endl;

  運(yùn)行結(jié)果:

  0x7b17d8

  0x7b17d8

  0x7b17f0

  0x7b17f0

  可以發(fā)現(xiàn),this 確實(shí)指向了當(dāng)前對象,而且對于不同的對象,this 的值也不一樣。

  幾點(diǎn)注意:

  this 是 const 指針,它的值是不能被修改的,一切企圖修改該指針的操作,如賦值、遞增、遞減等都是不允許的。

  this 只能在成員函數(shù)內(nèi)部使用,用在其他地方?jīng)]有意義,也是非法的。

  只有當(dāng)對象被創(chuàng)建后this 才有意義,因此不能在 static 成員函數(shù)中使用(后續(xù)會(huì)講到 static 成員)。

  this 到底是什么

  this 實(shí)際上是成員函數(shù)的一個(gè)形參,在調(diào)用成員函數(shù)時(shí)將對象的地址作為實(shí)參傳遞給 this。不過 this 這個(gè)形參是隱式的,它并不出現(xiàn)在代碼中,而是在編譯階段由編譯器默默地將它添加到參數(shù)列表中。

  this 作為隱式形參,本質(zhì)上是成員函數(shù)的局部變量,所以只能用在成員函數(shù)的內(nèi)部,并且只有在通過對象調(diào)用成員函數(shù)時(shí)才給 this 賦值。

【C++ this指針詳解】相關(guān)文章:

c++函數(shù)指針使用示例07-26

C++函數(shù)指針學(xué)習(xí)教程05-21

C語言指針函數(shù)和函數(shù)指針詳解12-08

C語言數(shù)組與指針詳解08-15

C語言的指針類型詳解05-21

C語言指針用法詳解04-17

C++ 中引用和指針的關(guān)系04-01

c語言指針中的二級(jí)指針示例詳解03-02

c++快速排序詳解04-24