c ++ study notes: About const int * & and the difference between & const int * const - the new "const" role or a reference to a pointer?

Existing procedures are as follows:

 1 int compare(const int &num1, const int *&num2)
 2 {
 3     return (num1 > *num2) ? num1 : *num2;
 4 }
 5 
 6 int main()
 7 {
 8     int i = 9;
 9     int temp = 7;
10     int *p = &temp;
11     compare(i, p);
12     return 0;
13 }

Will lead the line 11 at compile error: not to initialize the value "const int * &" type of use "int *" value type, which means that we provide arguments "p" is illegal.

We know the type of pointers and references must be consistent with the type and it points to the referenced object, but there is one exception to this is the constant pointing pointer can point to const object, and the constant references can be any expression initialized, our parameter requirements it is a common reference, so the type of reference must be consistent with its reference to the type of object, in order to let our heads function can be used in more places, so we decided to "common references" declared as "const reference", change the function declaration the following form:

/ * 
 * Function header before the change: int the Compare (const int & num1, const int * & num2) 
 * function header after the change: int the Compare (const int & num1, const int * const & num2) 
 * / 

int the Compare ( const  int & num1, const  int * const & num2) 
{ 
    return (num1> * num2) num1:? * num2; 
} 

int main () 
{ 
    int I = . 9 ;
     int TEMP = . 7 ;
     int * P = & TEMP; 
    Compare (I, P) ; 
    return  0 ; 
}

The program should compile, we can get the desired result after running. At this time, the variable "num2" type is the "constant pointer to a constant reference."

 

In summary, you can learn the new "const" is acting on the reference.

Guess you like

Origin www.cnblogs.com/u-n-owen/p/11540129.html
Recommended