First, the concept
When the const is modified in front of the function name is the function return value, after the function name is a constant member function, the function can not modify any member within the object, only read operation, cannot occur write operation.
Second, the principle:
We all know that when invoking a member function, the compiler passes the address of the object itself as a hidden parameter to the function, and in the const member function, it cannot change the object to which this is directed, nor can it change the address that this is saved in. The type of this is a const pointer to the Const type object.
Specific examples:
After a function name has a const, this function must be a member function, that is, the normal function can not have const decoration, such as: int print () const {...} This function must be a member function, that is, a function defined within a class.
Once a const member function is defined in a class, this function cannot modify the member variables in the class, if a const object of a class is defined (non-const objects can call the const member function and non-const member Hanshu), it can only invoke the const member function in the class. Such as:
Class text{
Public
void Print_const (void) const {cout<< "Hello" <<ENDL;} has a const modifier
void print (void) {cout<< "Hello" <<ENDL;} No const modifiers
void getk (void) const {k=5;} Error, there is a const modifier, cannot modify the value of K,
Private
int k;
};
const text A;
int main ()
{
A.print (); Error, the const object can only be called
A.printf_const (); That's right
}
void print () const {} and void print () {} are overloaded functions, and if the object is const, the Void print () const member function is called, or void print () if it is non-const;
Class text{
Public
void print (void) const {cout<< "Hello_const" <<ENDL;}
void print (void) {cout<< "Hello" <<ENDL;}
};
const text A;
int main ()
{
A.print (); Screen output Hello_const If object A is defined as text A, the output hello
return 0;
}
The difference between a const in a "go" C + + and a function name