Reproduced to: http://www.cppblog.com/Marcky/archive/2009/07/12/89796.html
C ++ primer mentions that "only when the form parameter is a reference or pointer, whether the form parameter is const affects the carrying capacity ."
Int add (int A, int B );
Int add (const int A, const int B );
I want to define these two functions to realize whether the real parameter is a const overload. This is counterproductive. Here, the second function does not overloading the first one, but redefinition. Because the form parameters of the two functions are not directly associated with the real parameters, when the two functions are called, the form parameters are only a copy of the real parameters, no matter what processing the parameter is done in the Add function, it does not affect the real parameter. That is to say, the const In the second function parameter is useless. So the second definition here is just a redefinition of the first one.
Int add (Int & A, Int & B );
Int add (const Int & A, const Int & B );
The difference between the two functions defined this time is that the reference is used for the form parameter. At this time, the compiler can determine which function to call based on whether the real parameter is const. The call is as follows:
// Non-const variables X, Y
Int x = 1;
Int y = 2;
Add (x, y); // call add (Int & A, Int & B)
// Const variable X, Y
Const int x = 1;
Const int y = 2;
Add (x, y); // call add (const Int & A, const Int & B)
The first case above: when the real parameter is a non-const object, both functions can be called and matched, because non-const objects can not only initialize non-const references, you can also initialize the const reference. However, since non-const objects involve type conversion when initializing const references, the function with non-const reference parameters is the best match.
The second case above: when the real parameter is a const object, this object cannot be passed to a function with a non-const reference, because the const object can only be used to initialize the const reference. Int add (int * a, int * B );
Int add (const int * a, const int * B );
// Non-const object
Int x = 1;
Int y = 2;
// Cosnt object
Const int r = 1;
Const int S = 2;
Add (& X, & Y); // call add (int * a, int * B );
Add (& R, & S); // call add (cosnt int * a, cosnt int * B );
It is also legal to overload a parameter with a const pointer. The principle is the same as that of a const reference parameter.
It should be noted that the overload is implemented based on whether the pointer itself is const, rather than whether the object pointed to by the pointer is const.