c ++ referenced in the points to note

1, a null reference does not exist. Reference must be connected to a legitimate memory.

2, once the reference is initialized to a target, it can not be directed to another object. Pointer can point to another object at any time.

3, reference must be initialized when created. Pointer may be initialized at any time.

4, C ++ provides a variable passed by reference. Parameter is a reference variable, and argument is a variable, the function is called, parameters (reference variable) to point argument variable unit. This argument may be changed by the value of parameter reference.

5, when the function returns a reference time, a pointer to an implicit return value is returned. In this way, it can function on the left side of an assignment statement. In the following example:

#include <the iostream> the using namespace STD; Double Vals [] = { 10.1 , 12.6 , 33.1 , 24.1 , 50.0 }; Double & the setValues ( int i) 
{ return Vals [i];    // return a reference to the i-th element } // to call the function defined above the main function int main () 
{ 
   COUT << " value before change " << endl;
    for ( int I = 0 ; I < . 5 ; I ++
 
 
 

 

  

 


  )
   { 
       COUT << " Vals [ " << << I " ] = " ; 
       COUT << Vals [I] << endl; 
   } 
 
   the setValues ( . 1 ) = 20.23 ; // change the second element of 
   the setValues ( . 3 ) = 70.8 ;   // change the fourth element 
 
   COUT << " value change " << endl;
    for ( int I = 0 ; I < . 5 ;i ++ ) 
   { 
       cout<< "vals[" << i << "] = ";
       cout << vals[i] << endl;
   }
   return 0;
}

When the above code is compiled and executed, it produces the following results:

Value before change 
Vals [ 0 ] = 10.1 
Vals [ . 1 ] = 12.6 
Vals [ 2 ] = 33.1 
Vals [ . 3 ] = 24.1 
Vals [ . 4 ] = 50 
the changed value 
Vals [ 0 ] = 10.1 
Vals [ . 1 ] = 20.23 
Vals [ 2 ] = 33.1 
Vals [ . 3 ] = 70.8 
Vals [ . 4 ] = 50

When returning a reference, pay attention to the referenced object can not exceed the scope. So to return a reference to a local variable is not legitimate, however, can return a reference to a static variable.

int & FUNC () {
    int Q;
    // return Q;! // error occurs at compile time 
   static  int X;
    return X;      // security, x in the function remains valid outside the scope 
}

6, Continued

Guess you like

Origin www.cnblogs.com/cqu-qxl/p/11455570.html