您的位置:首页 > 其它

引用和使用引用传递参数《二》

2012-09-17 21:08 302 查看
使用引用传递参数

在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 3
1	3
1	3


//其值不会交换。

再来看一下引用传递

/*
* 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 3
1	3
3	1
================================


当然你还可以用指针变量作为函数参数,效果和引用传递一样。

 

/*
* 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:65
67
65	67
67	65
=======================================


你还可以交换指针变量所保存的地址哦。

/*
* 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:56
67
56	67
56	67
56	67
67	56
================================================


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: