C ++通过参考程序 [英] C++ Pass by Reference Program

查看:132
本文介绍了C ++通过参考程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IBM在下面的示例中解释了C ++通过引用传递(包括源代码)。

IBM explains C++ pass by reference in the example below (source included).

如果我将 void swapnum ... 更改为 void swapnum j),它会变成值吗?

If I changed void swapnum... to void swapnum(int i, int j), would it become pass by value?

// 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;
}

来源

推荐答案

如果你通过值传递的任何交换只会影响或看到它们传递的函数,而不是调用代码。此外,一旦你回到主,你会看到a和b没有交换。这就是为什么当交换数字你想通过参考。

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. 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.

以下是一个示例:

#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;
}

运行此代码,您应该看到更改仅通过引用也就是在我们返回到main之后,值被交换。如果你通过值,你会看到调用这个函数并返回到main,实际上a和b没有交换。

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.

这篇关于C ++通过参考程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆