參考

參考 在 C++

1 個練習

關於 參考

複製與 References

以我們目前的知識來說,要透過函式來更新變數有點麻煩。 每個函式引數都會以複製的方式處理,不會更動原始的值。 視你的型別大小而定,這可能對程式碼的效能造成嚴重影響。

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 編輯 連結會在新視窗或分頁中開啟

學習 參考