Kodewick
開始學 →
引用10 / 30

C++ 引用

第 10 課,共 30 課 · 第 2 部分 · 流程和函式 · 約 15 分鐘

引用是一個變數的別名,寫成 int& r = x;,改 r 就是改 x;引數寫成引用,函式就能改外面的變數,const std::string& 傳參還能省掉複製。

上一課說過:傳值時,函式拿到的是一份複製,改不到外面的變數。這一課講 C++ 的另一種辦法:引用。引用就是一個變數的另一個名字。

main.cpp
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 指向的是誰。

堆疊

scoreint80
refint&

ref 沒有自己的格子:它只是 score 的另一個名字

一個東西,兩個名字

通過哪個名字改,另一個名字看到的都一樣:

main.cpp
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}

一開始就繫結,以後不換

引用在宣告時就必須說清楚是誰的名字。只寫 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}
單選

程式裡已經有 int x = 1;。哪一行會編譯錯誤?

引用引數:改到外面

引用真正好用的地方是函式引數。引數寫成引用,它就是呼叫時那個變數的另一個名字,函數裡改它,外面的變數就變了:

main.cpp
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}
練習 1

清零

寫一個函式 reset,用引用引數把外面的變數改成 0。程式要顯示 0。

要顯示
0
exercise1.cpp
1#include <iostream>2 3int main() {4    int count = 42;5    reset(count);6    std::cout << count << '\n';7    return 0;8}
輸出
點「執行」或按 Ctrl+Enter
練習 2

修好它:分數沒有加上

apply_curve 本想給分數加 5 分,可分數還是 70。只加一個字元,讓程式顯示 75。

要顯示
75
exercise2.cpp
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}
輸出
點「執行」或按 Ctrl+Enter

交換兩個數

交換兩個變數的值,是引用引數的經典例子。傳值的話,函式換的只是兩份複製;用引用,換的就是外面的兩個變數:

main.cpp
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 以後它就丟了。

堆疊

xint3
yint8
aint&
bint&
tempint3

a 和 b 是 x 和 y 的另一個名字;temp 先把 a 的值存下來

標準庫裡已經有現成的:#include <utility> 以後寫 std::swap(x, y);,做的是同樣的事。

排順序拖動或點箭頭排順序

把交換的三行排好,讓程式顯示 8 3。

  1. a = b;
  2. b = temp;
  3. int temp = a;
要顯示
8 3
練習 3

把小的放前面

寫一個函式 sort_two(int& a, int& b):如果 a 比 b 大,就交換它們。呼叫以後 low 是小的那個。程式要顯示 4 9。

要顯示
4 9
exercise3.cpp
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}
輸出
點「執行」或按 Ctrl+Enter

引用要有一個變數

int& 引數要的是一個能改的變數。給它一個數,或者一個算式的結果,編譯器不答應:

main.cpp
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;

const 引用

傳值會複製一份。一個 int 複製起來不費事,可一個很長的 std::string(以後還有裝著幾千個元素的容器),每呼叫一次就複製一遍,就浪費了。

這時用 const 引用:const std::string& text。& 表示不復制,直接用外面那個;const 表示函式只看不改,改了就是編譯錯誤。

main.cpp
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 各管什麼?

怎麼傳引數

想要寫法例子
只看,型別很小傳值int n、double price、char c、bool ok
只看,型別可能很大const 引用const std::string& name
要改外面的變數引用int& score

一個函式可以混著用:

main.cpp
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),不改它。引數怎麼寫最合適?

這一課學會了

  • 引用是變數的另一個名字:int& ref = score;,通過哪個名字改都一樣。
  • 引用宣告時就要繫結(int& ref; 是編譯錯誤),繫結以後不能換;ref = y 是把值複製過去。
  • 引數寫成引用(int& score),函式就能改到外面的變數;swap 是經典例子,標準庫有 std::swap。
  • int& 只能繫結到變數,不能繫結到 90 或 score + 5 這樣的臨時值。
  • const std::string&:不復制、也不改,還能接臨時的值;大的東西只看不改時這樣傳。
  • 小型別只看就傳值,大的只看傳 const 引用,要改就傳引用。
第 10 課學完了嗎?第 10 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 11 課 · 15 分鐘vector用 std::vector 存一組資料:建立、push_back 往後加、size()、下標 v[i] 和 at(i)、越界會怎樣、front、back、pop_back、empty,傳給函式。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。