P10-c++ object and class-03this pointer is introduced in detail, and a detailed example is demonstrated

Article Directory

1. The role of this pointer

Assuming the following piece of code, the name of the formal parameter of the Demo class's constructor is the same as the name of the member variable, what will happen?

#include <iostream>
 /*
    author:梦悦foundation
    公众号:梦悦foundation
    可以在公众号获得源码和详细的图文笔记
*/
using namespace std;

class Demo {
    
    
private:
	int iDemo;
public:
	Demo(int iDemo);
	void Show();
};

Demo::Demo(int iDemo)
{
    
    
	iDemo = iDemo;
}

void Demo::Show()
{
    
    
	cout << "iDemo:" << iDemo << endl;
}
int main(int argc, char *argv[]) 
{
    
    
	cout << "---------------开始--->公众号:梦悦foundation---------------" << endl;
	Demo d1(2);
	d1.Show();
	cout << "---------------结束--->公众号:梦悦foundation---------------" << endl;
    return 0;
}

Originally call Demo d1(2)is expected to set the value of this member variable iDemo for 2, but the actual printing results:

meng-yue@ubuntu:~/MengYue/c++/object_class/03$ ./this_pointer
---------------开始--->公众号:梦悦foundation---------------
iDemo:32764
---------------结束--->公众号:梦悦foundation---------------
meng-yue@ubuntu:~/MengYue/c++/object_class/03$

It is found that the result is not what we expected.
The solution given by C++ is this 指针that it represents the currently accessed object.
So change the above constructor assignment statement to the following, and it will be fine.

this->iDemo = iDemo;

The result of compiling and running!

meng-yue@ubuntu:~/MengYue/c++/object_class/03$ ./this_pointer
---------------开始--->公众号:梦悦foundation---------------
iDemo:2
---------------结束--->公众号:梦悦foundation---------------
meng-yue@ubuntu:~/MengYue/c++/object_class/03$

Note:
Every member function (including constructor and destructor) has a this pointer.
This pointer points to the calling object.
If the method needs to refer to the entire call object, you can use an expression *this.
Use the const qualifier after the parentheses of the function to limit this to const, so that this cannot be used to modify the value of the object. However, it is not this to return, because this is the address of the object, but the object itself, ie *this(将解除引用运算符*用于指针,将得到指针指向的值). Now, you can use *this as the alias of the calling object to complete the previous method definition.

Guess you like

Origin blog.csdn.net/sgy1993/article/details/113575815