必备技能6.2:C++中参数的传递方式
缺省情况下,C++使用的是传值的方式。这就意味着函数中的代码对形参值的改变不会影响调用时传入的实参的值。在本书中,到目前为止的所有程序都是传值的方式传递参数的。例如,我们可以看一下下面程序中的函数reciprocal():
// 传值的方式中,对形参值的改变不会影响实参的值
#include <iostream>
using namespace std;
double reciprocal(double x);
int main()
{
double t = 10.0;
cout << "Reciprocal of 10.0 is " << reciprocal(t) << '/n';
cout << "Value of t is still: " << t << "/n";
return 0;
}
// 返回一个数的倒数
double reciprocal(double x )
{
x = 1 / x; //这里对x值的修改不会影响传入的t的值
return x;
}
在函数reciprocal()中我们修改了局部变量x的值。在main()函数中传入的实参t的值是不受影响的,在调用了reciproacl()函数后,其值还是10。