this pointer
In a class, there is a very hidden special pointer, which is the this pointer !
Why is it special? Because as long as a class is defined, the system will predefine a pointer named this and pointing to the current object. Although we can't see it we can use it.
For example, let's look at a member function of a clock class, the code used to set the time value:
intClock::SetTime(inth,intm,ints){H=h;M=m;S=s;}You can see that the member variables of the Clock class itself are H, M, and S. They need to be assigned values from the outside. In order to distinguish them, we define the formal parameters in lowercase. So if we know the existence of this, we can write like this:
intClock::SetTime(inth,intm,ints){this->H=h;this->M=m;this->S=s;}//It can also be written as: intClock::SetTime(inth,intm,ints ){(*this).H=h;(*this).M=m;(*this).S=s;}It can be seen that the above two writing methods use the hidden this pointer in the object, which can clearly be a member of this class, thus clearly distinguishing this object from external variables. In fact, when an object calls its member function, even if there are multiple objects of this class in the program, there is only one code for the member function. Therefore, in order to distinguish which object calls the member function, the compiler also converts It is used in the form of this->member function.