C ++ references function parameters as function parameters
A reference can also be used as a function parameter. For example, we define the swap function to exchange two numbers and define the function parameters as references:
1 void swap (int & p1, int & p2) // the parameters of the function here reference 2 {3 int p; 4 p = p1; 5 p1 = p2; 6 p2 = p; 7}
To call the function in a program, you can call the function directly using the variable as the real parameter at the call point of the corresponding main function, without any special requirements on the real variable. As defined above, the swap function can be written as follows:
Int main () {int a, B; cin> a> B; // enter the value of swap (a, B) in variables a and B ); // call the swap function directly using the variables a and B as the real parameters to cout <a <''<B; return 0 ;}
When a function is called, Real Variable a and variable B at the call point of the main function are passed to the called function parameters p1 and p2, respectively, since the parameters p1 and p2 are defined as references, p1 is the reference of the real parameter a, and p2 is the reference of the real parameter B. Therefore, in the called swap function, any operation on the parameters p1 and p2 is essentially an operation on the real parameters a and B.
Therefore, pay attention to the following points:
- The effect of passing a reference to a function is the same as that of passing a pointer. In this case, the parameter of the called function is used as the real parameter variable or an alias of the object in the original main function, therefore, the operations on the parameters in the called function are the operations on the corresponding target object (in the main function;
- Parameters that use the reference function do not generate a copy of the real parameter in the memory (because the reference is only the alias of the target variable rather than a new variable), and it directly operates on the real parameter; when using common variables to pass function parameters, You need to allocate storage units to the parameters when a function call occurs. In this way, different storage units are used for the parameters, so the copy of the real variable when the value of the parameter is changed. Therefore, when the amount of data transmitted by parameters is large, it is better to use references.
- Although using a pointer as a function parameter can achieve the same effect as using a reference, in the called function, you must repeat the operation in the form of "* pointer variable name, errors are easy to generate and the program reading is poor.
I am self-taught. The teaching materials may be a little old. If you have any questions, please correct me !!! Thank you !!!