第五章 函数
因为传值不能交换两个数的值,所以本节介绍了两种可以交换两数值的方法,分别为:传指针方式、传引用方式。
传指针方式:
#include <iostream>
using namespace std;
void swap(int *px,int *py);
int main()
{
int a=2,b=3;
swap(a,b);
cout<<a<<" "<<b<<endl;
return 0;
}
void swap(int *px,int *py)
{
int temp;
temp=*px;
*px=*py;
*py=temp;
}
得到的结果 为:3 2
在之后我将swap函数实现语句中的整型指针参数改为整型参数,
并未改变函数定义中的整型指针形参,却发现得到的结果仍是3 2
修改的部分如下:
void swap(int *px,int *py)
{
int temp;
temp=px;
px=py;
py=temp;
}
但是当将函数定义中的swap函数参数也改成了swap(int px,int py),之后再运行时发现两个数的值未发生交换。(未想通为何是如此的)
传引用方式
#include <iostream>
using namespace std;
void swap(int &x,int &y);
int main()
{
int a=2,b=3;
swap(a,b);
cout<<a<<" "<<b<<endl;
return 0;
}
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
当改变swap函数实现中的参数时(将其&去除)发现此时代码不能正确编译。