Practices are as follows:
#include <iostream> using namespace std; // Common exchange, the value of ab noted here, in particular when the call is a copy of the basic data, the original data does not change // thus the exchange value will not change here void the swap ( int A, int B) { int = tmp A; a = b; b = tmp; } // reference to the exchange, and the parameters of the original data point to the same place, can also be understood as a pointer to void refSwap ( int & A, int & B) { // need to define the value of the temporary variable tmp is stored int tmp = A; a = b; b = tmp; } // pointer to the exchange, the original data point to the same parameters and a local void pointSwap ( int * A, int * B) { // need to define the value of the temporary variable tmp is stored int tmp = * A; // pointer to the address value of the swap * * = A B; * B = tmp; } int main () { COUT << " reference pointer swap function & Practice: " << endl; int A = . 11 ; int B = 22 is ; cout << " temporary variable exchange: " << endl; swap(a, b); cout << "a:" << a << endl; cout << "b:" << b << endl; COUT << " pass by reference exchange: " << endl; // NOTE: invoked passed by reference, can simply pass the ordinary constants // herein may be combined function parameters, & a = a, so that here only write A refSwap (A, B); cout << "a:" << a << endl; cout << "b:" << b << endl; COUT << " pointer exchange: " << endl; // NOTE: When invoked with a pointer, and needs & // herein may be combined with the function parameter, * a = & a, so there need to take the write address & pointSwap (& A, & B) ; cout << "a:" << a << endl; cout << "b:" << b << endl; cout << "end." << endl; return 0; }
Output is as follows: