با دانش فعلی ما، بهروزرسانی یک متغیر به کمک یک تابع کمی دستوپاگیر است. با هر آرگومان تابع مثل یک کپی رفتار میشود و مقدار اصلی را تغییر نمیدهد. بسته به اندازهی نوع شما، این موضوع میتواند پیامدهای جدی برای کارایی کدتان داشته باشد.
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!