传递的价值,结果呢?

dou*_*gle 7 c++

可能重复:
通过引用传递或通过值传递?
在C++中通过引用/值传递

我遇到了pass-by-value-result方法的问题.我理解通过引用传递和传递值,但我不太清楚传值值的结果.通过值有多相似(假设它是相似的)?

这是代码

#include <iostream>
#include <string.h>
using namespace std;

void swap(int a, int b)
{

  int temp;
    temp = a;
    a = b;
    b = temp;
}

int main()
{
  int value = 2;
  int  list[5] = {1, 3, 5, 7, 9};


  swap(value, list[0]);

  cout << value << "   " << list[0] << endl;

  swap(list[0], list[1]);

  cout << list[0] << "   " << list[1] << endl;

  swap(value, list[value]);

  cout << value << "   " << list[value] << endl;

}
Run Code Online (Sandbox Code Playgroud)

现在的目标是找出"值"和"列表"的值是什么,如果你使用pass by value结果.(不通过价值).

Gen*_*ume 7

如果您通过值传递,那么您将在方法中复制变量.这意味着对该变量所做的任何更改都不会发生在原始变量上.这意味着您的输出如下:

2   1
1   3
2   5
Run Code Online (Sandbox Code Playgroud)

如果你被引用,它是通过你的变量的地址(而不是制作一份拷贝),然后通过你的输出会有所不同,并会反映互换进行的计算(INT A,INT B).你运行它来查看结果吗?

编辑经过一些研究后我发现了一些东西.C++不支持按值传递结果,但可以模拟它.为此,您可以创建变量的副本,通过引用将其传递给函数,然后将原始值设置为临时值.见下面的代码..

#include <iostream>
#include <string.h>
using namespace std;

void swap(int &a, int &b)
{

  int temp;
    temp = a;
    a = b;
    b = temp;
}

int main()
{
  int value = 2;
  int  list[5] = {1, 3, 5, 7, 9};


  int temp1 = value;
  int temp2 = list[0]

  swap(temp1, temp2);

  value = temp1;
  list[0] = temp2;

  cout << value << "   " << list[0] << endl;

  temp1 = list[0];
  temp2 = list[1];

  swap(list[0], list[1]);

  list[0] = temp1;
  list[1] = temp2;

  cout << list[0] << "   " << list[1] << endl;

  temp1 = value;
  temp2 = list[value];

  swap(value, list[value]);

  value = temp1;
  list[value] = temp2;
  cout << value << "   " << list[value] << endl;

}
Run Code Online (Sandbox Code Playgroud)

这将为您提供以下结果:

1   2
3   2
2   1
Run Code Online (Sandbox Code Playgroud)

这种类型的传递也称为Copy-In,Copy-Out.Fortran使用它.但这就是我在搜索过程中发现的全部内容.希望这可以帮助.

  • 如果是copy-in,copy-out,您不应该将值复制到临时变量,调用swap,并在swap调用后重新分配目标值吗?第一个调用看起来是正确的,但如果我理解正确,您希望每次都传入 `temp1` 和 `temp2` 以进行交换。 (2认同)