C++ 中的参数传递方式有2中,pass by value 和 pass by reference,传递数值和传递引用,两者最主要的区别在于
pass by value: 将数值copy一份给形参,形参数值的改变不影响形参;
pass by reference : 形式参数能访问参数,形式参数和被穿参数为同一内存地址,形参的改变会引起被传递参数的改变;
如果不希望改变被传递参数的数值,建议在函数定义的时候函数头中采用 constant 关键字,表示被传递参数数值不会改变。
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;
}
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;
}