C++中的“this”指针

要理解“this”指针,重要的是要了解对象如何看待类的函数和数据成员。

1)每个对象都有自己的数据成员副本。

2)所有人都访问与代码段中相同的函数定义。

意味着每个对象都有自己的数据成员副本,并且所有对象共享成员函数的单个副本。

现在的问题是,如果每个成员函数只有一个副本并且被多个对象使用,那么如何访问和更新适当的数据成员?

编译器提供一个隐式指针以及函数名“this”。

“ this”指针作为隐藏参数传递给所有非静态成员函数调用,并且可用作所有非静态函数主体中的局部变量。“ this”指针在静态成员函数中不可用,因为可以在没有任何对象(带有类名)的情况下调用静态成员函数。

对于X类,此指针的类型为“ X *”。另外,如果X的成员函数声明为const,则此指针的类型为“ const X *”。

C++通过调用以下代码让对象销毁自身:

<code>delete this;/<code>

以下是使用“ this”指针的情况:

1)当本地变量的名称与成员的名称相同时

<code>#include 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; } /<code>

输出:

<code>x = 20/<code>

对于构造函数,当参数名称与成员名称相同时,也可以使用初始化程序列表。

2)返回对调用对象的引用

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

当返回对本地对象的引用时,返回的引用可用于链接单个对象上的函数调用。

<code>#include using namespace std; class Test { private: int x; int y; public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test &setX(int a) { x = a; return *this; } Test &setY(int b) { y = b; return *this; } void print() { cout << "x = " << x << " y = " << y << endl; } }; int main() { Test obj1(5, 5); // Chained function calls. All calls modify the same object // as the same object is returned by reference obj1.setX(10).setY(20); obj1.print(); return 0; } /<code>

输出:

<code>x = 10 y = 20/<code>