按照我们目前掌握的知识,借助函数来更新变量还有点麻烦。 每个实参都按副本处理,不会改变原来的值。 而根据类型的大小,这可能对代码的性能造成严重影响。
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!