In the use of C + + language development, if we want an object to be defined without being incorrectly modified, we can declare the object as a const object so that the data members of the object cannot be changed.
1. Define a Const object
Const class name Object name;
Class name const object name;
1 when defining a class object, you can designate it as a const object. After definition, the Const object can no longer be modified;
2 The Const object cannot invoke a member function of a non-const type.
Within a non-const member function, it is possible to modify the object's data members, such as Sethour () to modify the hour value of the object. A member function of the const type does not modify the data members of the object.
Const data member
1.const data member
Use the const keyword inside a class to declare a const data member. The value of the const data member cannot be modified.
The const int m_nnum;//defines a const data member
Initialization is special and can only be initialized by initializing the list. Cannot assign a value in a constructor.
2. Initializing the list
The constructor initialization list begins with a colon, followed by a comma-separated list of data members followed by an initializer in parentheses.
Initialization lists can be initialized for data members, not just const data members.
We added an initialization list outside the constructor that gives the const member M_nnum an initial value of 10, and if we have more than one constructor, you must add an initialization list initialization to the const member outside each constructor, including the copy constructor.
Const member function
A 1.CONST member function can only be referenced by a const object;
A const data member can be referenced within a 2.CONST member function, or it can refer to a non-const data member, but cannot modify the value of a non-const data member or call a non-const member function.
3.const member functions must be added with const when declaring and defining them.
Original link: http://www.maiziedu.com/wiki/cplus/const/