1 值传递
实现两个数字进行交换,代码和运行结果如下所示:
#include<iostream>
using namespace std;
void change(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "change a = " << a << endl;
cout << "change b = " << b << endl;
}
int main()
{
int a = 1;
int b = 2;
change(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
system("pause");
return 0;
}
从运行结果可以看出,通过函数进行值传递,实参(a、b)并不会发生改变,change(int a, int b)函数中进行形参的改变。
2、地址传递
通过指针的方式进行地址的传递,代码如下所示:
#include<iostream>
using namespace std;
void change(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
cout << "change a = " << *a << endl;
cout << "change b = " << *b << endl;
}
int main()
{
int a = 1;
int b = 2;
change(&a, &b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
system("pause");
return 0;
}
运行结果如下所示:
从结果可知,通过指针传递的是地址,改变的是实际参数(a、b)的值。
上文如有错误 恳请各位大佬指正。