Original link: http://www.cnblogs.com/xudong-bupt/p/3509567.html
Usually in writing C + + code when not pay attention to the use of const, has long been the usage of the const forget
Write a little something to deepen the impression
#include <iostream>using namespace Std;int main () { int a1=3; Non-const data const int A2=A1; Const data int * a3 = &a1; Non-const data,non-const pointer const int * a4 = &a1; Const DATA,NON-CONST Pointer int * Const A5 = &a1; Non-const data,const pointer int CONST * CONST A6 = &a1; Const DATA,CONST Pointer const INT * Const A7 = &a1; Const DATA,CONST pointer return 0;}
One of the things that makes the sense that const is particularly anti-human is that he appears on the left side, modifying the data content on the right, which is the pointer when it appears on the right.
Const modifier member function
(1) Const-Modified member function cannot modify any member variable (except mutable-Modified variable )
(2) The const member function cannot call a non-const member function because non-const member functions can modify member variables
#include <iostream>using namespace Std;class point{public : Point (int _x): X (_x) {} void testconstfunction (int _x) const{/// error, in the const member function, you cannot modify any class member variable x=_x; Error, the const member function cannot call a non-ONST member function because a non-const member function can modify the member variable modify_x (_x); } void modify_x (int _x) { x=_x; } int x;};
Value passing
If the function return value is in "value passing", the const modifier has no value because the function copies the return value into an external temporary storage unit. So, for value passing, the addition of Const does not make much sense.
So:
Do not write the function int GetInt (void) as a const int GetInt (void).
Do not write function a geta (void) as const a geta (void), where a is a user-defined data type.
Summary: use const as much as possible in your programming, so you can get the help of a compiler to write robust code.
[Use of const in]c++