Turn from: http://blog.csdn.net/feixiaoxing/article/details/6786622
Const is a key word in C + + language, but if used well, it can greatly improve the robustness of the code. In general, the use of const is still quite a lot of places, but mainly in the following areas: (1) The protection of ordinary variables, (2) The protection of address space, (3) the Declaration and protection of class initial variables, and (4) the protection of class variables in functions. The protection of const is primarily from the compiler level and is not related to the operation of the program.
(1) Protection of common variables
View plain const int data = 10; const char str = ' a '; Const double PI = 3.14; The code above is the definition of a set of global variables, and if the variable changes in the function, the code fails to compile.
(2) Protection of address space
View plain void process () {int value = 10; Const int* Address = &value; Unlike the code above, this is where the code will fail if the value that the address points to is changed. You can add *address = 100 before the end of the function; try it.
(3) The definition of a class const member variable
View Plain class Desk {const int price; Public:desk ():p rice () {} ~desk () {}}; A const member variable is a const keyword that is added before a class variable is defined. Unlike ordinary member variables, the const variable must be initialized in the constructor. If there is no const keyword, then it is not necessary to initialize it within the constructor.