When a query function has the same name as a change function and the number and type of parameters are the same, the difference between the two is that one has a const and the other has no Const.
A common application of const overload is the subscript operator. Generally, we should try to use standard template containers, such as STD: vector, but sometimes we need to support subscript operators in our own classes. An empirical rule is that subscript operators usually appear in pairs.
Class Fred {...};
Class myfredlist {
Public:
Const Fred & operator [] (unsigned index) const; operator subscript operator usually appears in pairs
Fred & operator [] (unsigned index); operator subscript operators are usually paired
...
};
When the subscript operator is used for a non-const myfredlist object, the compiler calls the non-const table operator. Because a normal Fred & is returned, the corresponding Fred object can be viewed or modified. For example, assume that the Fred class has a viewing function FRED: inspect () const and a change function FRED: mutate ():
Void F (myfredlist & A) except myfredlist is not const
{
// You can call a method without modifying the Fred object at a [3:
Fred x = A [3];
A [3]. Inspect ();
// You can call the method to modify the Fred object at a [3:
Fred y;
A [3] = y;
A [3]. mutate ();
}
However, when a const myfredlist object uses the subscript operator, the compiler calls the const subscript operator. Because const Fred & is returned, you can view the corresponding Fred object and cannot modify it.
void F (const myfredlist & A) When myfredlist is const
{< br> // you can call the method of the Fred object without modifying a [3:
Fred x = A [3];
A [3]. inspect ();
// error (lucky !): Try to change the Fred object from a [3]:
Fred y;
A [3] = y; fortunately, the compiler found this error during compilation.
A [3]. mutate (); the compiler is lucky to find this error during compilation.
}