C++ Notes 16: const Basics

Note 16 Regarding the const keyword, the behavior of const is different in C and C++.

Let's take a look at the const basics first.

Basic understanding of const: const is to define constants, const means read-only.

The most basic key to mastering const is: a pointer variable and the memory space variable it points to are two different concepts, depending on whether const modifies the pointer itself or modifies the memory space pointed to by the pointer.

 

for example:

 

Define a structure Teacher. In the operatorTeacher01 function, the function parameter is const Teacher *pt, and the memory space pointed to by the pointer cannot be modified. If you try to modify the memory space pointed to by the pointer pt->age=10 , a compilation error will occur.

In the operatorTeacher02 function, the function parameter Teacher *const pt, this sentence means that pt cannot be modified, that is, the pointer cannot be modified, but the memory space pointed to by the pointer can be modified.

Looking at the function operatorTeacher03(const Teacher *const pt), according to the formal parameters, the pt pointer cannot be modified, and the memory space pointed to by the pointer cannot be modified.

Run the program:

age:33

Please press any key to continue...


 

 

 

long press to unlock

 

Unlock more exciting insider

 

programming according to the law

WeChat: Lightspeed-Tech

Technology drives life

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212653&siteId=291194637