简体   繁体   English

C ++通过引用程序

[英]C++ Pass by Reference Program

IBM explains C++ pass by reference in the example below (source included). IBM在下面的示例(包括源代码)中通过引用解释了C ++传递。

If I changed void swapnum... to void swapnum(int i, int j) , would it become pass by value? 如果我将void swapnum...更改为void swapnum(int i, int j) ,它将通过值传递吗?

// pass by reference example
// author - ibm

#include <stdio.h>

void swapnum(int &i, int &j) {
  int temp = i;
  i = j;
  j = temp;
}

int main(void) {
  int a = 10;
  int b = 20;

  swapnum(a, b);
  printf("A is %d and B is %d\n", a, b);
  return 0;
}

Source 资源

Any swapping performed if you pass by value are only affected or seen within the function they are passed into and not the calling code. 如果您按值传递,则执行的任何交换都只会影响或看到传递给函数的值,而不会传递给调用代码。 In addition, once you return back to main you will see that a and b did not swap. 此外,返回主菜单后,您将看到a和b没有交换。 That is why when swapping numbers you want to pass by ref. 这就是为什么交换数字时要通过引用传递的原因。

If you are just asking if that is what it would be called, then yes you are right, you would be passing by value. 如果您只是问那是什么,那是的,您是对的,您将按价值传递。

Here is an example: 这是一个例子:

#include <stdio.h>

void swapnum(int &i, int &j) {
  int temp = i;
  i = j;
  j = temp;
}

void swapByVal(int i, int j) {
  int temp = i;
  i = j;
  j = temp;
}

int main(void) {
  int a = 10;
  int b = 20;

  swapnum(a, b);
  printf("swapnum A is %d and B is %d\n", a, b);

  swapByVal(a, b);
  printf("swapByVal A is %d and B is %d\n", a, b);

  return 0;
}

Run this code and you should see that changes persist only by swapping by reference, that is after we've returned back to main the values are swapped. 运行此代码,您应该看到更改仅通过按引用交换而持久存在,也就是说,在我们返回主值之后,就交换了值。 If you pass by value, you will see that calling this function and returning back to main that in fact a and b did not swap. 如果按值传递,您将看到调用此函数并返回到main,实际上a和b并未交换。

是的,但这意味着swapnum将不再起作用,顾名思义

Yes. 是。 The '&' operator specifies that the parameter should point to the memory address of what was passed in. '&'运算符指定该参数应指向传入内容的内存地址。

By removing this operator, a copy of the object is made and passed to the function. 通过删除此运算符,可以创建对象的副本并将其传递给函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM