[C++] const modifier operator overloading and functions

Article directory


One, const

insert image description here

insert image description here

Here, because the hidden type of the parameter in Print is the (Date const this) type, and the parameter type we pass is the const Date type, the converted to the hidden this form is the const Date const this type, and the actual participation parameter does not conform to it, so an error will be reported. This is because of the amplification of permissions, from const Date to Date.

The authority can only be panned or zoomed out but not zoomed in . Wouldn’t it be nice if we changed the type of the formal parameter to the const type at the beginning? In this way, the actual parameter is of const type, which is the translation of the authority. The actual parameter is of Date type and passed to the formal parameter is the reduction of authority, because the formal parameter type is const

2. How to use

insert image description here

Add const after the function name. It cannot be inside the brackets, because a formal parameter this pointer is hidden inside, which cannot be changed.

``insert image description here

Summarize

After adding const to the member function: both ordinary and const types can be called

Q: Can all member functions be const?
Answer: Member variables that cannot be modified cannot be added.
Conclusion: As long as the member variables are not modified inside the member function, const should be added, so that both const and ordinary objects can be used.

Guess you like

Origin blog.csdn.net/m0_74774759/article/details/130853652