[C++ basic knowledge] this pointer

First, please read the following sample code:

class Date
{
    
     
public :
	 void Display ()
 	{
    
    
		cout <<_year<< "-" <<_month << "-"<< _day <<endl;
	}
 
 void SetDate(int year , int month , int day)
 {
    
    
  	 _year = year;
  	 _month = month;
	 _day = day;
 }
private :
     int _year ; // 年
     int _month ; // 月
     int _day ; // 日
};
int main()
{
    
    
	 Date d1, d2;
 	 d1.SetDate(2021,3,19);
	 d2.SetDate(2020,3,19);
	 d1.Display();
	 d2.Display();
	 return 0; 
}

Please think: There are two member functions SetDate and Display in the Date class. There is no distinction between different objects in the function body. When s1 calls the SetDate function
, how does the function know that the s1 object should be set instead of the s2 object?

C++ solves this problem by introducing the this pointer, that is: the C++ compiler adds a hidden pointer parameter to each "non-static member function", so that the pointer points to the current object (the object that calls the function when the function is running), All member variable operations in the function body are accessed through this pointer. It's just that all operations are transparent to the user, that is, the user does not need to pass, the compiler automatically completes.

Icon:
Insert picture description here

The nature of this pointer:

  1. Type of this pointer: class type * const
  2. Can only be used inside "member functions"
  3. The this pointer is actually a formal parameter of a member function. When an object calls a member function, the object address is passed to the this
    parameter as an actual parameter. So the this pointer is not stored in the object.
  4. this pointer is the first member of an implicit function pointer parameter, automatically passes generally through the ecx register by the compiler, the user does not need to
    pass

Guess you like

Origin blog.csdn.net/weixin_43962381/article/details/113835495