C++中参数传递方式

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;

}

小结

  1. 若在调用函数不希望改变被穿参数,采用pass by value 并在 函数定义时添加 constant 修饰符;
  2. pass by reference 有两种参数传递方法,一种通过 引用,另一种是指针;
  3. 若被传递参数数据量比较大,建议采用pass by reference.
    4.指针方式是将指针的数值传递给函数参数,而引用也是将变量的地址传递给 变量
posted @ 2021-07-10 16:54  徐徐前行  阅读(666)  评论(0编辑  收藏  举报