L-value specifies const object

Source: Internet
Author: User

 

In C ++, the member variable cannot be modified within the function body of the member function modified by const. This feature is used to ensure that some member functions do not modify the data due to the programmer's carelessness during implementation. It also indicates that the member functions are not modified. If you only need to return the member function of the member variable, it will be declared as the const type (the position of the const is after the list of function-defined parameters)

In addition, const member functions cannot call non-const member functions. This is because a non-const member function may change the value of the member variable, which is contrary to the definition of the const member function.

However, in some cases, you need to change the member variables in the const function. In this case, you need to set the member variable to the mutable type. For example

Class C

{

Public:

Void func (const Int & P) const

{

I = P;

}

PRIVATE:

Mutable int I;

};

If variable I is not declared as mutable, the compilation fails.

If the member variable is a class type or structure type, and the member function that calls these variables in the const function, in addition to mutable declaration, you can also use a work und:

Class D

{

Public:

Void OP (){}

}

Class C

{

Public:

Void func (const Int & P, D & D) const

{

I = P;

D. OP ();

}

PRIVATE:

Mutable int I;

D CD;

};

Then, during the call, the parameter D & D takes * this as the input, and can call non-const functions.

P.s recently read related articles and learned a method to call non-const member functions in const member functions. Is to use the const_cast <> operator. It can remove the const attribute and remove the violate attribute. The preceding example can be written as follows.

Void func () const

{

Const_cast <D *> (& CD)-> OP ();

}

It can also be compiled.

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.