C++入门经典-例5.18-通过引用交换数值
1:在C++中,函数参数的传递方式主要有两种,即值传递和引用传递。值传递是指在函数调用时,将实际参数的值赋值一份传递到调用函数中,这样如果在调用函数中修改了参数的值,其改变将不会影响到实际参数的值。而引用传递则恰恰相反,如果函数按引用方式传递,那么在调用函数中修改了参数的值,其改变会影响到实际参数。
示例代码如下:
// 5.18.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void swap(int & a,int & b)//此为引用传递方式
{
int tmp;
tmp=a;
a=b;
b=tmp;
}
void main()
{
int x,y;
cout << "请输入x" << endl;
cin >> x;
cout << "请输入y" << endl;
cin >> y;
cout<<"通过引用交换x和y"<<endl;
swap(x,y);
cout << "x=" << x <<endl;
cout << "y=" << y <<endl;
}
//通过引用传递后,原来的参数改变了
View Code
运行结果: