课后习题一

1.解释为什么程序1-7的交换函数没有把形参x和y所对应的实参的值交换。如何修改代码,使实参的值得到交换?

//交换两个整数的不正确的代码
void swap(int x, int y)
{
    int temp = x;
    x = y;
    y = temp;
}   


//正确答案
//英文答案

/*The function swap fails to swap the values of the actual parameters because x and y are value parameters. The invocation swap(a, b) results in the values of the actual parameters a and b being copied into the formal parameters x and y, respectively. Then, within the body of swap, the values of x and y are interchanged, and the function terminates. Upon termination, the new values of x and y are not copied back into the actual parameters. Consequently, the values of the actual parameters are unaffected by the function.
To get the function to work properly we should change the header to */

//我的看法:使用引用避免拷贝,将函数传形参改为传引用,引用改变了实参的值。当形参是引用类型时,形参对应的实参会被引用传递。所以实参的值会被交换。


void swap(int &x,int &y)
{
  int temp = x;
  x = y;
  y = temp;
}

posted @ 2017-08-30 10:38  御风少爷  阅读(208)  评论(0编辑  收藏  举报