上海龙凤419

C说话

C++ this指针详解

时候:2024-07-04 10:53:23 C说话 我要投稿
  • 相干保举

C++ this指针详解

  this 是 C++ 中的一个关头字,也是一个 const 指针,它指向今后工具,经由进程它能够拜候今后工具的统统成员。上面是小编为大师清算的C++ this指针详解,接待参考~

  所谓今后工具,是指正在利用的工具。比方对stu.show();,stu 便是今后工具,this 就指向 stu。

  上面是利用 this 的一个完全示例:

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

  }

  运转成果:

  李华的春秋是16,成便是96.5

  this 只能用在类的外部,经由进程 this 能够拜候类的统统成员,包含 private、protected、public 属性的。

  本例中成员函数的参数和成员变量重名,只能经由进程 this 辨别。以成员函数setname(char *name)为例,它的形参是name,和成员变量name重名,若是写作name = name;如许的语句,便是给形参name赋值,而不是给成员变量name赋值。而写作this -> name = name;后,=左侧的name便是成员变量,右侧的name便是形参,一目明了。

  注重,this 是一个指针,要用->来拜候成员变量或成员函数。

  this 固然用在类的外部,可是只要在工具被建立今后才会给 this 赋值,并且这个赋值的进程是编译器主动完成的,不须要用户干涉干与,用户也不能显式地给 this 赋值。本例中,this 的值和 pstu 的值是不异的。

  咱们没关系来证实一下,给 Student 类增加一个成员函数printThis(),特地用来输入 this 的值,以下所示:

  void Student::printThis(){

  cout<<this<<endl;

  }

  而后在 main() 函数中建立工具并挪用 printThis():

  Student *pstu1 = new Student;

  pstu1 -> printThis();

  cout<<pstu1<<endl;

  Student *pstu2 = new Student;

  pstu2 -> printThis();

  cout<<pstu2<<endl;

  运转成果:

  0x7b17d8

  0x7b17d8

  0x7b17f0

  0x7b17f0

  能够发明,this 确切指向了今后工具,并且对差别的工具,this 的值也不一样。

  几点注重:

  this 是 const 指针,它的值是不能被点窜的,统统诡计点窜该指针的操纵,如赋值、递增、递加等都是不许可的。

  this 只能在成员函数外部利用,用在其余处所不意思,也长短法的。

  只要当工具被建立后this 才成心思,是以不能在 static 成员函数中利用(后续会讲到 static 成员)。

  this 究竟是甚么

  this 现实上是成员函数的一个形参,在挪用成员函数时将工具的地点作为实参通报给 this。不过 this 这个形参是隐式的,它并不出此刻代码中,而是在编译阶段由编译器冷静地将它增加到参数列表中。

  this 作为隐式形参,实质上是成员函数的部分变量,以是只能用在成员函数的外部,并且只要在经由进程工具挪用成员函数时才给 this 赋值。

【C++ this指针详解】相干文章:

C说话指针函数和函数指针详解09-29

C说话的指针范例详解05-21

c++疾速排序详解10-18

C说话中指针变量作为函数参数详解07-01

C说话指针的观点08-20

若何懂得C说话指针05-19

C说话中的指针是甚么08-08

若何利用C说话数组指针09-14

C说话庞杂指针是甚么08-15

C说话中指针的观点03-16