当前位置:网站首页>Const decorated member function problem

Const decorated member function problem

2022-07-06 10:11:00 anieoo

C++ When defining class objects in this The pointer , Point to the object itself defined by the class .

this General purpose of pointer :
         When a parameter has the same name as a member variable , You can use this Pointer to distinguish
         Return the object itself in the class's non static member function , You can use return* this

When I try to modify this When the pointer points to , Find out vs Prompt error :

Found after review this The essence of a pointer is a pointer constant , The point of the pointer is not modifiable , namely :Person* const this;
however this The data of the object the pointer points to can be modified .

If you want the value pointed to by the pointer, you can't change , Statement is required Constant function . That is, in function const modification :

As you can see from the diagram const Modifying Member Functions , Data representing the memory space pointed to by the pointer cannot be modified . The function of this constant function is actually to this The pointer is added const Embellishment becomes const Type* const this; therefore this Neither the direction nor the value of the direction can be modified !!!!
       
however C++ Provides a way to modify in constant functions this The data of the memory space pointed to by the pointer , The box mutable Keywords modify variables .

  Similar to constant functions are Constant variable .

  utilize const Class name Variable name , Define constant variable . As you can see from the diagram Constant variables can only access the value of member variables , But it can't be modified , But it can be modified mutable key word Modified member variables .

  As can be seen from the above figure , Constant variables can only call constant functions , Ordinary member functions cannot be called !!!

 

原网站

版权声明
本文为[anieoo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131726124904.html