Error c2166: L-value specifies const object

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.