Const modifier pointer: If the keyword const appears on the left side of asterisk *, it indicates that the indicated object is a constant. If const appears on the right side of *, it indicates that the pointer itself is a constant, if it appears on both sides, it indicates that the things and pointers are constants;
Const STD: vector <int>: iterator iter = Vec. Begin (); // The role of ITER is like T * const; ++ ITER; Error
STD: vector <int >:: const_iterator citer = VEC. Begin (); // The role of citer is like a const T *; * citer = 10; Error
Const modifier function return value: declare operator *'s return value as const type to avoid (A * B) = C; this meaningless value assignment action
Const member function: indicates that the member function can act on the const object.
The two member functions have different constants and can be overloaded.
Bitwise constness: the const member function cannot change any non-static member variable of the object.
Class ctextblock {
Public:
STD: size_t length () const;
PRIVATE:
Char * ptext;
SDT: size_t textlength;
Bool lengthvalid;
};
STD: size_t ctextblock: length () const
{
If (! Lengthisvalid)
{
Textlength = STD: strlen (ptext); // error! You cannot assign a value to a const member function.
Lengthisvalid = ture; // textlength and lengthvalid
}
}
In this case, you can use a const-related swing field: mutable (variable) to release the bitwise constness constraint of the non-static member variable.
Class ctextblock {
Public:
STD: size_t length () const;
PRIVATE:
Char * ptext;
Mutable SDT: size_t textlength;
Mutable bool lengthvalid;
};
STD: size_t ctextblock: length () const
{
If (! Lengthisvalid)
{
Textlength = STD: strlen (ptext); // now textlength can be changed
Lengthisvalid = ture; // and lengthvalid
}
}
Avoid duplication in const member functions and non-const member functions: Call the const brother using non-const for two conversions. The reverse method should not be that the const member function does not change the logical state of the object.
Class textblock {
Public:
Const char & operator [] (STD: size_t position) const
{
......
Return text [opsition];
}
Char & operator [] (STD: size_t position)
{
Return
Const_cast <char &> (// remove the const of the return value of OP []
Static_cast <const textblock &> (* This) [] // call op [] to add const to * This
);
}
};