参照

参照 の C++

1個の演習

参照について

コピーと参照

現在の知識では、関数の助けを借りて変数を更新するのは少し面倒です。 関数への入力はすべてコピーのように扱われ、元の値は変わりません。 扱う型のサイズによっては、これがコードのパフォーマンスに深刻な影響を与えることがあります。

int adjust_salary(int base, int kids) {
    return base + kids * 500;
}
int now_a_mother_of_twins{2500};
adjust_salary(now_a_mother_of_twins, 2);

// now_a_mother_of_twins is still 2500
now_a_mother_of_twins = adjust_salary(now_a_mother_of_twins, 2);
// now_a_mother_of_twins is now 3500

Referencesは別名と考えることができます。それを変更すると、元の変数に影響します。 Referencesは、型の宣言でアンパサンド(&)を使います。

int balance{1000};
int& budget{balance};
int pro_computer_wheels{699};
budget -= pro_computer_wheels;
// budget is now 301;
// balance is also 301;

付け替え(referenceの束縛を変えること)はできません。 初期化されていないreferenceは作れません。 Referencesは、既存の変数で初期化する必要があります。

int main_acc{1'000'000};
int side_acc{-20};
int& savings{main_acc};
// => main_acc and savings are 1'000'000

// try to reseat savings to use main account
savings = side_acc;
// savings and main_acc are now -20
// as this uses the **value** of side_acc
savings += 20;
// savings and main_acc are now 0, side_acc is stil -20

int& future_budget;
// => compiler error, reference must be bound!

void

referencesの力を使えば、関数から値を返す必要がまったくないこともあります。 そういう場面では、戻り値の型としてvoidを使います。

void increase_power(int& level) {
    level += 500;
}
int goku{8700};
increase_power(goku);
// goku's power level?
// It's over 9000!
GitHubで編集 リンクは新しいウィンドウまたはタブで開きます

参照を学習する