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.