PASS Parameters Using references
In C ++, there are only two types of function parameter transfer: value transfer and reference transfer. The so-called value transfer refers to function call, pass the actual parameter value to
In this way, if the parameter value is modified in the called function, it will not change to the actual parameter value. If the function is passed by reference,
The parameter value is modified in the call function, which affects the actual parameter.
The classic example is two-digit exchange.
Let's take a look at the value transfer:
/** Main. CPP ** created on: 2012-9-17 * Author: China ***/# include <iostream> using namespace STD; void swap (int A, int B); int main (INT argc, char ** argv) {int X, Y; cout <"Please enter two number:"; CIN> x> Y; cout <x <'\ t' <Y <Endl; If (x <Y) {swap (x, y );} cout <x <'\ t' <Y <Endl; return 0;} void swap (int A, int B) {int temp; temp =; A = B; B = temp;} the running result is: please enter two number: 1 31313
// The value is not exchanged.
Let's take a look at the reference Transfer
/** Main. CPP ** created on: 2012-9-17 * Author: China ** use reference to pass Parameters **/# include <iostream> using namespace STD; void swap (Int &, int & B); int main (INT argc, char ** argv) {int X, Y; cout <"Please enter two number :"; cin> x> Y; cout <x <'\ t' <Y <Endl; If (x <Y) {swap (x, y );} cout <x <'\ t' <Y <Endl; return 0;} void swap (Int & A, Int & B) {int temp; temp =; A = B; B = temp;} the running result is: please enter two number: 1 31331 ======================================
Of course, you can also use pointer variables as function parameters, and the effect is the same as that transmitted by reference.
/** Main. CPP ** created on: 2012-9-17 * Author: China ***/# include <iostream> using namespace STD; void fun (int * a, int * B ); int main (INT argc, char ** argv) {int A, B; cout <"Please enter two number:"; CIN >>a> B; cout <A <'\ t' <B <Endl; fun (& A, & B ); cout <A <'\ t' <B <Endl; return 0;} // exchange void fun (int *, int * B) {int t; t = * A; * A = * B; * B = T;} Run and if it is: please enter two number: 656765676765 ==============================================
You can also switch the address saved by the pointer variable.
/** Main. CPP ** created on: 2012-9-17 * Author: China ***/# include <iostream> using namespace STD; int main (INT argc, char ** argv) {int, b; cout <"Please enter two number:"; CIN> A> B; cout <A <'\ t' <B <Endl; int * P, * P1, * P2; P1 = & A; P2 = & B; cout <* P1 <'\ t' <* P2 <Endl; if (A <B) // exchange address {P = p1; P1 = P2; P2 = P ;} // point to the changed cout <A <'\ t' <B <Endl; cout <* P1 <'\ t' <* P2 <Endl; return 0;} Run and if it is: please enter two number: 56675667566756676756 ============================================== ==========