一应和使用引用传递参数《二》
使用引用传递参数
在C++语言中,函数参数的传递只要有2种,分别为值传递和引用传递,所谓值传递,是指在函数调用时,将实际参数的值传递到调
用函数中,这样如果在调用函数中修改了参数的值,其不会改变到实际参数的值。二引用传递则相反,如果函数按引用方式传递,
在调用函数中修改了参数的值,其改变会影响到实际的参数。
经典的例子就是2个数交换。
先看一下值传递:
/* * 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;a=b;b=temp;}运行结果为:please enter two number:1 31313
//其值不会交换。
再来看一下引用传递
/* * 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;a=b;b=temp;}运行结果为:please enter two number:1 31331================================
当然你还可以用指针变量作为函数参数,效果和引用传递一样。
/* * 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;}//将两个指针变量所指向的数值进行交换void fun(int *a, int *b){int t;t = *a;*a = *b;*b = t;}运行及如果为:please enter two number:656765676765=======================================
你还可以交换指针变量所保存的地址哦。
/* * main.cpp * * Created on: 2012-9-17 * Author: china * * */#include <iostream>using namespace std;int main(int argc, char **argv) {int a, 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)//交换地址{p=p1;p1=p2;p2=p;}//指向发生变化cout << a << '\t' << b << endl;cout << *p1 << '\t' << *p2 << endl;return 0;}运行及如果为:please enter two number:56675667566756676756================================================