在编写个人函数的时候,你将受到C++中一条基本原则的限制:在默认的情况下,参数只能以值传递的方式给函数。
这句话的理解是:被传递到函数的只是变量的值,永远不会是变量本身。
例如:
#include <iostream>
using namespace std;
void changeAge(int age, int newage);
int main()
{
int age = 24;
cout << "My age is " << age << endl;
changeAge(age, age + 1);
cout << "Now my age is " << age << endl;
return 0;
}
void changeAge(int age, int newAge)
{
age = newAge;
cout << "In this, my age is " << age << endl;
}
这样的输出是:
My age is 24
In this, my age is 25
Now my age is 24
因为这里的“age”相当于是两个函数里面的变量,changeAge函数里面的“age”变量不能影响主函数里面的“age”变量
传址
为了绕开“值传递”问题,第一种方法就是向函数传递变量的地址取代它的值。正如我们所理解的,想要获取某个变量的地址只需在它前面加上一个“取地址”操作符“&”就行了。例如:
#include <iostream>
using namespace std;
void changeAge(int *age, int newAge);
int main()
{
int age = 24;
cout << "My age is " << age << endl;
changeAge(&age, age + 1);
cout << "Now my age is " << age << endl;
return 0;
}
void changeAge(int *age, int newAge)
{
*age = newAge;
cout << "In this, my age is " << *age << endl;
}
这次的输出就是:
My age is 24
In this, my age is 25
Now my age is 25
接下来是自己的一次尝试
#include <iostream>
using namespace std;
void swap(int *x, int *y);
int main()
{
int x = 1;
int y = 2;
cout << "现在x = " << x << ", y = " << y << endl;
swap(&x, &y);
cout << "现在x = " << x << ", y = " << y << endl;
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
这个代码就实现了对x和y的调换,自己写的
下面这个算是加深自己的理解,就是当时是这么想的,是否主函数里面的两个变量是否需要和下面的函数一样,所以就试了一下
#include <iostream>
using namespace std;
void swap(int *x, int *y);
int main()
{
int a, b;
cout << "请输入两个不同的值:" << endl;
cin >> a >> b;
swap(&a, &b);
cout << "现在a = " << a << ", b = " << b << endl;
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
这个也同样实现了上面的那个功能。
引用传递
设想如果事先就知道某个函数的参数只能接受一个地址,能不能使用某种约定使得在调用该函数时不需要使用指针的语法呢?
于是乎,以引用传递方式传递输入方式的概念因此而产生了。
其实它跟我们这个传址的目的是一样的,都是把地址传递给函数,但语法不同更加容易使用了。
#include <iostream>
using namespace std;
void swap(int &x, int &y);//注意这里和上面的不同,里面是地址
int main()
{
int x, y;
cout << " 请输入两个不同的值:" << endl;
cin >> x >> y;
swap(x, y);//这里也是直接在里面写变量名就可以了
cout << "现在x = " << x << ", y = " << y << endl;
return 0;
}
void swap(int &x, int &y)
{
x ^= y;
y ^= x;
x ^= y;