C++ Passing References as Parameters
We have already discussed how to use pointers to implement call-by-reference functions. The following example uses references to implement call-by-reference functions.
Example
#include <iostream>
using namespace std;
// Function declaration
void swap(int& x, int& y);
int main ()
{
// Local variable declaration
int a = 100;
int b = 200;
cout << "Before swap, value of a:" << a << endl;
cout << "Before swap, value of b:" << b << endl;
/*Call the function to swap values*/
swap(a, b);
cout << "After swap, value of a:" << a << endl;
cout << "After swap, value of b:" << b << endl;
return 0;
}
// Function definition
void swap(int& x, int& y)
{
int temp;
temp = x; /*Save the value at address x*/
x = y; /*Assign y to x*/
y = temp; /*Assign x to y*/
return;
}
When the above code is compiled and executed, it produces the following results:
交换前,a 的值: 100 交换前,b 的值: 200 交换后,a 的值: 200 交换后,b 的值: 100other extensions