C++ 中的参数传递方式有2中,pass by value 和 pass by reference,传递数值和传递引用,两者最主要的区别在于
pass by value: 将数值copy一份给形参,形参数值的改变不影响形参;
pass by reference : 形式参数能访问参数,形式参数和被穿参数为同一内存地址,形参的改变会引起被传递参数的改变;
如果不希望改变被传递参数的数值,建议在函数定义的时候函数头中采用 constant 关键字,表示被传递参数数值不会改变。
pass by value
int max( int x, int y)
{
if(x<=y)
{
x = y;
}
return x;
}
int main(void )
{
int x = 7,y =9;
cout<<"before" << endl;
cout<< "x value: " << x << " y value: " << y << endl;
cout<< "max : "<< max(x,y) << endl;
cout<<"after"<< endl;
cout<< "x value: " << x << " y value: " << y << endl;
return 0;
}
pass by reference
一种采用引用的方式调用;另一种采用指针调用。
引用
int max( int& x, int& y)
{
if(x<=y)
{
x = y;
}
return x;
}
int main(void )
{
int x = 7,y =9;
cout<<"before" << endl;
cout<< "x value: " << x << " y value: " << y << endl;
cout<< "max : "<< max(x,y) << endl;
cout<<"after"<< endl;
cout<< "x value: " << x << " y value: " << y << endl;
return 0;
}
指针
int max( int* x, int* y)
{
if(x<=y)
{
*x = *y;
}
return *x;
}
int main(void )
{
int x = 7,y =9;
cout<<"before" << endl;
cout<< "x value: " << x << " y value: " << y << endl;
cout<< "max : "<< max(&x,&y) << endl;
cout<<"after"<< endl;
cout<< "x value: " << x << " y value: " << y << endl;
return 0;
}
小结
- 若在调用函数不希望改变被穿参数,采用pass by value 并在 函数定义时添加 constant 修饰符;
- pass by reference 有两种参数传递方法,一种通过 引用,另一种是指针;
- 若被传递参数数据量比较大,建议采用pass by reference.