//________________________________
//用地址传递的方式来实现两个数的交换
//________________________________
#include <iostream.h> void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; }
void main() { int val1 = 10, val2 = 20; cout << "Before swap, val1 =" << val1 << " " << "val2 =" << val2 << endl;
swap(&val1,&val2); cout << "After swap, val1 =" << val1 << " " << "val2 =" << val2 <<endl;
}
注:指针作为函数参数,提供了一种可以间接修改调用该函数参数值的手段。
//________________________________
//用引用参数的方式来实现两个数的交换
//________________________________
#include <iostream.h> void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; }
void main() { int val1 = 10, val2 = 20; cout << "Before swap, val1 =" << val1 << " " << "val2 =" << val2 << endl;
swap(val1,val2); cout << "After swap, val1 =" << val1 << " " << "val2 =" << val2 <<endl;
}
注:引用是它所引用的常量或变量的一个别名,它们实际上是同一回事。同样,当函数的形式参数是引用类型时,它实际上是对实在参数所代表的变量或常量的引用,它自己不具有独立的内存空间。