如何使用 C++ 中的引用参数?
ここでは、C++ で変数の参照を渡す方法について見ていきます。これは「Call by Reference」と呼ばれることもあります。
Call by Reference という関数の引数を渡す方法は、引数の参照を正式パラメータにコピーします。関数内部では、参照を使用して呼び出しで使用された実際の引数にアクセスします。つまり、パラメータに加えた変更は渡された引数に影響を与えます。
値を参照で渡すには、通常の値と同じように引数参照を関数に渡します。したがって、以下の swap() 関数のように、関数パラメータを参照型として宣言する必要があります。swap() 関数は、2 つの整数変数の値を入れ替えます。
例
// 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;
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP