c ++, references, their understanding of it

/ * This example demonstrates a method of exchanging three variable values:
. 1) swap1 () parameters directly transmitted the content, we can not achieve the purpose of the exchange value of the two numbers. For swap1 () is, a, b is the parameter is limited to the scope of local variables inside a function, which has its own memory, and num1, num2 refers to the data are not the same. Value respectively num1, num2 passed to a, b the function is called, thereafter num1, num2, and a, b no longer any relationship in swap1 () Internal Review a, b values do not affect the function of the external num1, num2, It will not change num1, num2's value.

2) swap2 () is passed a pointer, it is possible to achieve the purpose of the exchange value of the two numbers. When calling the function, respectively num1, num2 the pointer to p1, p2, after p1, p2 points a, b represent the data, change the values a, b indirectly through pointers within the function. We " C language pointer variable as a function of the parameter " also been compared the difference between 1), 2) in FIG.

2) swap3 () is passed by reference, it is possible to achieve the purpose of the exchange value of the two numbers. When you call the function, respectively r1, r2 bound to num1, num2 that the referenced data, then r1 and num1, and num2 r2 to represent the same data, and modify data after r1 will affect num1, modify data by r2 after also affect num2. * /

 

#include <iostream>
using namespace std;
void swap1(int a, int b);
void swap2(int *p1, int *p2);
void swap3(int &r1, int &r2);
int main() {
int num1, num2;
cout << "直接传递: "<<endl;
cin >> num1 >> num2;
swap1(num1, num2);
cout << num1 << " " << num2 << endl;
cout << "传递指针: "<<endl;
cin >> num1 >> num2;
swap2(&num1, &num2);
cout << num1 << " " << num2 << endl;
cout << "按引用传参: "<<endl;
cin >> num1 >> num2;
swap3(num1, num2);
cout << num1 << ""Num2 << << endl; A = B;int TEMP = A;void swap1 (A int, int B) {// parameter content transmitted directly}
return 0;





TEMP = B;
}
// pass a pointer
void swap2 (P1 int *, int * P2) {
int * TEMP = P1;
* = P1 * P2;
* P2 = TEMP;
}
// parameter passing by reference
void swap3 (int & r1 , int & R2) {
int TEMP = R1;
R1 = R2;
R2 = TEMP;
}

Guess you like

Origin www.cnblogs.com/qianrushi1/p/11564344.html