C++ this指针

来源:这里教程网 时间:2026-02-16 16:04:59 作者:

this指针保存当前对象的地址,简单来说,你可以说这个指针指向该类的当前对象。让我们举个例子来理解这个概念。

C++ 示例:this指针

在这里你可以看到我们有两个数据成员num和ch。在成员函数setMyValues()中,我们有两个与数据成员名称相同的局部变量。在这种情况下,如果要将局部变量值赋值给数据成员,那么除非使用this指针,否则您将无法执行此操作,因为除非您使用this,否则编译器将不知道您指的是对象的数据成员。这是必须使用this指针的示例之一。

#include <iostream>using namespace std;class Demo {private:  int num;  char ch;public:  void setMyValues(int num, char ch){    this->num =num;    this->ch=ch;  }  void displayMyValues(){    cout<<num<<endl;    cout<<ch;  }};int main(){  Demo obj;  obj.setMyValues(100, 'A');  obj.displayMyValues();  return 0;}

输出:

100A

示例 2:使用this指针进行函数链式调用

使用this指针的另一个示例是返回当前对象的引用,以便您可以链式调用函数,这样您就可以一次调用当前对象的所有函数。在这个程序中需要注意的另一个要点是,我在第二个函数中增加了对象num的值,你可以在输出中看到它实际上增加了我们在第一个函数调用中设置的值。这表明链接是顺序的,对对象的数据成员所做的更改将保留以进一步链式调用。

#include <iostream>using namespace std;class Demo {private:  int num;  char ch;public:  Demo &setNum(int num){    this->num =num;    return *this;  }  Demo &setCh(char ch){    this->num++;    this->ch =ch;    return *this;  }  void displayMyValues(){    cout<<num<<endl;    cout<<ch;  }};int main(){  Demo obj;  //Chaining calls  obj.setNum(100).setCh('A');  obj.displayMyValues();  return 0;}

输出:

101A

相关推荐