如何在C ++中使用参考参数?

在这里,我们将看到如何在C ++中传递某些变量的引用。有时我们称其为“按引用致电”。

将参数传递给函数的按引用调用方法会将参数的引用复制到形式参数中。在函数内部,引用用于访问调用中使用的实际参数。这意味着对参数所做的更改会影响传递的参数。

为了通过引用传递值,参数引用与任何其他值一样传递给函数。因此,相应地,您需要像下面的函数中那样将函数参数声明为引用类型,该函数swap()交换其参数所指向的两个整数变量的值。

示例

// function definition to swap the values.
void swap(int &x, int &y) {
   int temp;
   temp = x; /* save the value at address x */
   x = y; /* put y into x */
   y = temp; /* put x into y */
   return;
}

现在,让我们swap()通过引用传递值来调用函数,如以下示例所示:

示例

#include <iostream>
using namespace std;
//函数声明
void swap(int &x, int &y);
int main () {
   //局部变量声明:
   int a = 100;
   int b = 200;
   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;
   /* calling a function to swap the values using variable reference.*/
   swap(a, b);
   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
   return 0;
}

输出结果

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100