Mutable is an uncommon keyword in C ++. It can only be used for non-static and non-constant data members of a class.
We know that the state of an object is determined by the non-static data member of the object. As the data member changes,
The status of the object also changes!
If a member function of a class is declared as the const type, this function will not change the object state, that is
This function does not modify non-static data members of the class, but sometimes it is necessary
Assign a value. This requires the mutable keyword.
For example:
Class demo
{
Public:
Demo (){}
~ Demo (){}
Public:
Bool getflag () const
{
M_naccess ++;
Return m_bflag;
}
PRIVATE:
Int m_naccess;
Bool m_bflag;
};
Int main ()
{
Return 0;
}
Compile the aboveCodeThe error c2166: L-value specifies const object will occur.
It indicates that the non-static data member of the class is changed in the const type function.
In this case, you need to use mutable to modify the non-static data member to be changed in the const member function.
M_naccess, the Code is as follows:
Class demo
{
Public:
Demo (){}
~ Demo (){}
Public:
Bool getflag () const
{
M_naccess ++;
Return m_bflag;
}
PRIVATE:
Mutable int m_naccess;
Bool m_bflag;
};
Int main ()
{
Return 0;
}
In this way, no errors will occur during re-compilation!
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/gengxt2003/archive/2008/07/26/2715746.aspx