C++ 引用
引用是一個變數的別名,寫成 int& r = x;,改 r 就是改 x;引數寫成引用,函式就能改外面的變數,const std::string& 傳參還能省掉複製。
上一課說過:傳值時,函式拿到的是一份複製,改不到外面的變數。這一課講 C++ 的另一種辦法:引用。引用就是一個變數的另一個名字。
1#include <iostream>2 3int main() {4 int score = 80;5 int& ref = score;6 ref += 5;7 std::cout << score << '\n';8 std::cout << ref << '\n';9 return 0;10}
85 85
int& ref = score; 讀作「ref 是 score 的引用」。型別後面的 & 表示引用。ref 不是一個新的變數,沒有自己的值;它和 score 是同一個東西的兩個名字。所以 ref += 5 改的就是 score。點單步,看畫面上 ref 指向的是誰。
堆疊
scoreint80refint&一個東西,兩個名字
通過哪個名字改,另一個名字看到的都一樣:
1#include <iostream>2 3int main() {4 double price = 20;5 double& p = price;6 price = 25;7 std::cout << p << '\n';8 p = p * 0.8;9 std::cout << price << '\n';10 return 0;11}
25 20
改 price,p 看到 25;改 p,price 變成 20。拿 int 變數做引用就寫 int&,double 就寫 double&,std::string 就寫 std::string&。
小技巧: int& ref 和 int &ref 是一樣的,空格放哪邊都行。這門課把 & 貼著型別寫。
這段程式顯示什麼?
1#include <iostream>2 3int main() {4 int a = 1;5 int& b = a;6 b = b + 1;7 a = a * 10;8 std::cout << a << " " << b << '\n';9 return 0;10}
b 是 a 的另一個名字。b = b + 1 讓 a 變成 2,a = a * 10 再變成 20。只有一個變數,兩個名字讀到的都是 20。一開始就繫結,以後不換
引用在宣告時就必須說清楚是誰的名字。只寫 int& ref; 是編譯錯誤,g++ 會說 'ref' declared as reference but not initialized(聲明瞭引用卻沒有初始化)。
繫結以後,它一輩子都是那個變數的名字,換不了。之後再寫 ref = 別的變數,只是把值複製過去:
這段程式顯示什麼?
1#include <iostream>2 3int main() {4 int x = 3;5 int y = 8;6 int& r = x;7 r = y;8 y = 100;9 std::cout << x << " " << r << '\n';10 return 0;11}
r 一直是 x 的名字。r = y 不是讓 r 改去當 y 的名字,而是把 y 的值 8 存進 x。後來 y 變成 100,和 x 沒關係,所以 x 和 r 都是 8。程式裡已經有 int x = 1;。哪一行會編譯錯誤?
int& r; 沒有繫結任何變數,編譯不過。int r; 是普通變數,可以先不給值。引用引數:改到外面
引用真正好用的地方是函式引數。引數寫成引用,它就是呼叫時那個變數的另一個名字,函數裡改它,外面的變數就變了:
1#include <iostream>2 3void add_bonus(int& score) {4 score += 10;5}6 7int main() {8 int score = 80;9 add_bonus(score);10 std::cout << score << '\n';11 return 0;12}
90
和上一課只差一個 &,結果從 80 變成了 90。點單步:進入 add_bonus 時,畫面上多了一層,可裡面的 score 不是一個新的數,而是指向 main 裡的 score。
void add_bonus(int score)80函數裡改的是複製的那份void add_bonus(int& score)90score 就是 main 裡的 score呼叫的地方看不出來引數是不是引用:add_bonus(score) 兩種寫法都一樣。所以要改外面變數的函式,名字最好說清楚它會改,比如 add_bonus、reset。
這段程式顯示什麼?
1#include <iostream>2 3void twice(int& n) {4 n = n * 2;5}6 7int main() {8 int a = 3;9 twice(a);10 twice(a);11 std::cout << a << '\n';12 return 0;13}
n 是 a 的另一個名字,每呼叫一次,a 就乘 2:3 變 6,再變 12。清零
✓寫一個函式 reset,用引用引數把外面的變數改成 0。程式要顯示 0。
0
1#include <iostream>2 3int main() {4 int count = 42;5 reset(count);6 std::cout << count << '\n';7 return 0;8}
修好它:分數沒有加上
✓apply_curve 本想給分數加 5 分,可分數還是 70。只加一個字元,讓程式顯示 75。
75
1#include <iostream>2 3void apply_curve(int score) {4 score += 5;5}6 7int main() {8 int score = 70;9 apply_curve(score);10 std::cout << score << '\n';11 return 0;12}
交換兩個數
交換兩個變數的值,是引用引數的經典例子。傳值的話,函式換的只是兩份複製;用引用,換的就是外面的兩個變數:
1#include <iostream>2 3void swap_values(int& a, int& b) {4 int temp = a;5 a = b;6 b = temp;7}8 9int main() {10 int x = 3;11 int y = 8;12 swap_values(x, y);13 std::cout << "x = " << x << ", y = " << y << '\n';14 return 0;15}
x = 8, y = 3
點單步,看 a 和 b 分別指向誰,temp 怎麼幫忙:先把 a 的值存起來,不然 a = b 以後它就丟了。
堆疊
xint3yint8aint&bint&tempint3標準庫裡已經有現成的:#include <utility> 以後寫 std::swap(x, y);,做的是同樣的事。
把交換的三行排好,讓程式顯示 8 3。
a = b;b = temp;int temp = a;
8 3
temp 存下 a 的值,再讓 a = b,最後把存著的值給 b。要是先寫 a = b;,a 原來的 3 就找不回來了。把小的放前面
✓寫一個函式 sort_two(int& a, int& b):如果 a 比 b 大,就交換它們。呼叫以後 low 是小的那個。程式要顯示 4 9。
4 9
1#include <iostream>2 3int main() {4 int low = 9;5 int high = 4;6 sort_two(low, high);7 std::cout << low << " " << high << '\n';8 return 0;9}
引用要有一個變數
int& 引數要的是一個能改的變數。給它一個數,或者一個算式的結果,編譯器不答應:
1#include <iostream>2 3void add_bonus(int& score) {4 score += 10;5}6 7int main() {8 int score = 80;9 add_bonus(90);10 std::cout << score << '\n';11 return 0;12}
main.cpp: In function 'int main()':
main.cpp:9:15: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
9 | add_bonus(90);
| ^~cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int':int& 不能繫結到一個臨時的值上。90 不是哪個變數,加了 10 也沒地方放,所以不讓。add_bonus(score + 5) 也一樣。
哪一個呼叫能通過編譯?
1void add_bonus(int& score);2 3int score = 80;
int& 引數要的是一個能改的變數。90 和 score + 5 都是臨時算出來的值,不是哪個變數,加了 10 也沒地方放。const 引用
傳值會複製一份。一個 int 複製起來不費事,可一個很長的 std::string(以後還有裝著幾千個元素的容器),每呼叫一次就複製一遍,就浪費了。
這時用 const 引用:const std::string& text。& 表示不復制,直接用外面那個;const 表示函式只看不改,改了就是編譯錯誤。
1#include <iostream>2#include <string>3 4int count_char(const std::string& text, char c) {5 int n = 0;6 for (std::size_t i = 0; i < text.size(); i++) {7 if (text[i] == c) {8 n++;9 }10 }11 return n;12}13 14int main() {15 std::string fruit = "banana";16 std::cout << count_char(fruit, 'a') << '\n';17 std::cout << count_char("apple", 'p') << '\n';18 return 0;19}
3 2
const 引用還有個好處:它可以繫結到臨時的值上,所以 count_char("apple", 'p') 這樣直接給一個字串也行。反正不會改它,不怕沒地方放。(迴圈裡的 std::size_t 是 size() 給出的型別,一種不會是負數的整數,下一課細講。)
const std::string& text 裡,& 和 const 各管什麼?
& 讓 text 成為外面那個字串的另一個名字,所以不用複製;const 保證函式只看不改,改了就是編譯錯誤。怎麼傳引數
| 想要 | 寫法 | 例子 |
|---|---|---|
| 只看,型別很小 | 傳值 | int n、double price、char c、bool ok |
| 只看,型別可能很大 | const 引用 | const std::string& name |
| 要改外面的變數 | 引用 | int& score |
一個函式可以混著用:
1#include <iostream>2#include <string>3 4void add_item(const std::string& name, double price, double& total) {5 total += price;6 std::cout << name << ":" << price << " 元\n";7}8 9int main() {10 double total = 0;11 add_item("牛奶", 6.5, total);12 add_item("麵包", 12, total);13 std::cout << "合計:" << total << " 元\n";14 return 0;15}
牛奶:6.5 元 麵包:12 元 合計:18.5 元
name 只看不改,用 const 引用;price 是個小小的 double,傳值;total 要一路加上去,用引用。
函式只顯示一個人的名字(std::string),不改它。引數怎麼寫最合適?
const 引用:不復制,也不會改到。std::string& name 讓函式能改外面的名字,還不能接 "小林" 這樣直接寫的字串;std::string name 能用,但每次都要複製一份。這一課學會了
- 引用是變數的另一個名字:
int& ref = score;,通過哪個名字改都一樣。 - 引用宣告時就要繫結(
int& ref;是編譯錯誤),繫結以後不能換;ref = y是把值複製過去。 - 引數寫成引用(
int& score),函式就能改到外面的變數;swap是經典例子,標準庫有std::swap。 int&只能繫結到變數,不能繫結到90或score + 5這樣的臨時值。const std::string&:不復制、也不改,還能接臨時的值;大的東西只看不改時這樣傳。- 小型別只看就傳值,大的只看傳
const引用,要改就傳引用。