Kodewick
開始學 →
從 C 過來29 / 30

學過 C 的人看這裡

第 29 課,共 30 課 · 第 7 部分 · 再往前 · 約 15 分鐘

學過 C 再學 C++,最先換掉的是:printf 換成 std::cout,char 陣列換成 std::string,陣列和 malloc 換成 std::vector。

C++ 是從 C 長出來的,大部分 C 程式碼拿到 C++ 編譯器裡也能編譯。可「能編譯」不等於「該這樣寫」:這門課前面講的很多東西,就是用來代替 C 裡那些容易出錯的寫法的。這一課把它們並排放在一起:先是 C 的寫法(只是給你看,不執行),再是 C++ 的寫法(可以執行)。沒學過 C 也可以讀,就當是複習。

一個小例子,C 裡你會這樣寫:

1#include <stdio.h>2 3int main(void) {4    printf("Hello, %s! You are %d.\n", "Ana", 30);5    return 0;6}

C++ 裡這樣寫:

main.cpp
1#include <iostream>2#include <string>3 4int main() {5    std::string name = "Ana";6    int age = 30;7    std::cout << "Hello, " << name << "! You are " << age << ".\n";8    return 0;9}
輸出
Hello, Ana! You are 30.

printf 換成 cout

printf 靠格式符認型別:%d 配 int,%f 配 double。寫錯了(比如 %d 配上一個 double),編譯器最多給個警告,執行時顯示一個怪數。std::cout 自己知道每個值的型別,不需要格式符,也就不會配錯。

printfprintf("%d\n", 2.5);一個怪數%d 配上了 double
coutstd::cout << 2.5;2.5不用格式符
printf 靠格式符說型別,配錯了編譯器不攔著;cout 自己認得每個值的型別

要控制小數位和寬度,用第 3 課的 <iomanip>:

1printf("單價:%.2f\n", price);2printf("合計:%8.2f\n", price * count);
main.cpp
1#include <iomanip>2#include <iostream>3 4int main() {5    double price = 6.5;6    int count = 3;7    std::cout << std::fixed << std::setprecision(2);8    std::cout << "單價:" << price << '\n';9    std::cout << "合計:" << std::setw(8) << price * count << '\n';10    return 0;11}
輸出
單價:6.50
合計:   19.50

%.2f 對應 std::fixed << std::setprecision(2),設一次,後面一直有效;%8.2f 裡的 8 對應 std::setw(8),只管緊跟著的那一個值。

注意: C 的標頭檔在 C++ 裡也能用,名字去掉 .h、前面加 c:<stdio.h> 是 <cstdio>,<math.h> 是 <cmath>,<string.h> 是 <cstring>。std::printf 照樣能用,但一個程式裡最好只選一種輸出方式。

單選

C 裡的 printf("%.2f\n", price);,在 C++ 裡怎麼寫?

char 陣列換成 std::string

C 的字串是 char 陣列加結尾的 '\0':要自己算好陣列夠不夠大,複製用 strcpy,拼接用 strcat,比較用 strcmp,寫錯一個就越界。

1char full[32];2strcpy(full, "Ana");3strcat(full, " Silva");4if (strcmp(full, "Ana Silva") == 0) {5    printf("%s, %zu letters\n", full, strlen(full));6}

std::string 自己管記憶體,多長都放得下;複製是 =,拼接是 +,比較是 ==:

main.cpp
1#include <iostream>2#include <string>3 4int main() {5    std::string full = "Ana";6    full += " Silva";7    if (full == "Ana Silva") {8        std::cout << full << "," << full.size() << " 個字元\n";9    }10    std::string copy = full;11    copy[0] = 'E';12    std::cout << full << " / " << copy << '\n';13    return 0;14}
輸出
Ana Silva,9 個字元
Ana Silva / Ena Silva

copy = full 是真的複製了一份,改 copy 不影響 full。在 C 裡,兩個 char* 之間寫 = 只是讓兩個指標指著同一塊記憶體。

C:char *char *b = a;改 b,a 也變兩個指標指著同一塊
C++:std::stringstd::string b = a;改 b,a 不變b 有自己的一份
C 裡兩個 char* 之間的 = 只複製位址;std::string 的 = 複製整段文字
猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <string>3 4int main() {5    std::string s = "ab";6    s += "cd";7    std::cout << s.size() << '\n';8    return 0;9}
練習 1

不用 strcat 的全名

用 std::string 把 first 和 last 拼成全名(中間一個空格),顯示全名和它的字元個數,像這樣:Ana Silva(9 個字元)。

要顯示
Ana Silva(9 個字元)
exercise1.cpp
1#include <iostream>2#include <string>3 4int main() {5    std::string first = "Ana";6    std::string last = "Silva";7 8    return 0;9}
輸出
點「執行」或按 Ctrl+Enter

陣列換成 vector

C 的陣列傳給函式時,只傳過去一個指標,長度得另外傳:

1double average(const double *a, int n) {2    double total = 0;3    for (int i = 0; i < n; i++) total += a[i];4    return total / n;5}

std::vector 自己知道有幾個元素,還能 push_back 變長:

main.cpp
1#include <iostream>2#include <vector>3 4double average(const std::vector<double>& temps) {5    double total = 0;6    for (double t : temps) {7        total += t;8    }9    return total / temps.size();10}11 12int main() {13    std::vector<double> temps{18.5, 21.0, 19.5};14    temps.push_back(23.0);15    std::cout << temps.size() << " 天,平均 " << average(temps) << " 度\n";16    return 0;17}
輸出
4 天,平均 20.5 度

const std::vector<double>& 不復制、也不改,相當於 C 裡的 const double * 加上長度。

單選

C 的陣列傳給函式時,為什麼還要另外傳一個長度 n?

malloc 和 free

C 裡要一塊大小執行時才知道的記憶體,就 malloc,用完 free。忘了 free 是洩漏,free 兩次或者 free 以後還用,都是最難找的錯。

1int n = 5;2int *squares = malloc(n * sizeof(int));3for (int i = 0; i < n; i++) squares[i] = i * i;4free(squares);

C++ 裡,要一排元素就用 vector;要單獨一個放在堆上的物件,用第 21 課的 std::unique_ptr。兩者都會自己把記憶體還掉,不用寫 free,也不用寫 delete:

main.cpp
1#include <iostream>2#include <memory>3#include <string>4#include <vector>5 6struct Account {7    std::string owner;8    double balance;9};10 11int main() {12    int n = 5;13    std::vector<int> squares(n);14    for (int i = 0; i < n; i++) {15        squares[i] = i * i;16    }17    std::cout << "最後一個:" << squares[n - 1] << '\n';18    auto acc = std::make_unique<Account>();19    acc->owner = "小林";20    acc->balance = 120.5;21    std::cout << acc->owner << ":" << acc->balance << '\n';22    return 0;23}
輸出
最後一個:16
小林:120.5

squares 和 acc 在 main 結束時自己把記憶體還掉。點單步,走到最後看堆上的塊消失。C++ 裡也有 malloc,但它只給一塊生的記憶體,不呼叫建構函式,std::string 這樣的成員放進去就壞了:在 C++ 裡別用它。

堆疊

squaresvector<int>
accunique_ptr<Account>

堆

0 1 4 9 16int[5]
"小林" 120.5Account

squares 和 acc 管著堆上的記憶體:main 結束時它們析構,記憶體自己就還掉了
練習 2

不用 malloc 的一排數

n 是執行時才知道的個數。不用 malloc,用 std::vector<int> 放 1 到 n 每個數的 3 倍,再一行顯示出來,空格隔開。

要顯示
3 6 9 12 15 18 
exercise2.cpp
1#include <iostream>2#include <vector>3 4int main() {5    int n = 6;6 7    return 0;8}
輸出
點「執行」或按 Ctrl+Enter

struct、nullptr、bool

C 裡用 struct 常常要先 typedef 一下,不然每次都得寫 struct Point;空指標寫 NULL;真假要麼用 int,要麼包含 <stdbool.h>。

1typedef struct {2    int x;3    int y;4} Point;5 6Point *p = NULL;7int found = 0;

C++ 裡 struct 的名字直接就是型別名,不用 typedef;空指標寫 nullptr;bool 是內建的型別:

main.cpp
1#include <iostream>2 3struct Point {4    int x;5    int y;6};7 8int main() {9    Point a{3, 4};10    Point* p = nullptr;11    bool found = false;12    if (p == nullptr) {13        p = &a;14        found = true;15    }16    std::cout << std::boolalpha << found << " " << p->x << "," << p->y << '\n';17    return 0;18}
輸出
true 3,4

NULL 在 C++ 裡其實是一個整數 0,傳給過載的函式時,可能挑中引數是整數的那個版本,也可能乾脆挑不出來;nullptr 只能當指標,不會弄混。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2 3struct Point {4    int x;5    int y;6};7 8int main() {9    Point a{3, 4};10    Point* p = nullptr;11    std::cout << std::boolalpha << (p == nullptr) << " ";12    p = &a;13    std::cout << p->y << '\n';14    return 0;15}

指標引數換成引用

C 裡函式要改呼叫者的變數,只能傳指標,呼叫時寫 &,函數裡到處寫 *:

1void add_tax(double *price) {2    *price = *price * 1.1;3}4add_tax(&price);

C++ 用第 10 課的引用:函數裡像用普通變數一樣用,呼叫時也不用寫 &:

main.cpp
1#include <iostream>2 3void add_tax(double& price) {4    price = price * 1.1;5}6 7int main() {8    double price = 100;9    add_tax(price);10    std::cout << "含稅:" << price << '\n';11    return 0;12}
輸出
含稅:110

引用不會是空的,也不能改去指別的變數,所以比指標少了很多出錯的地方。只讀的大物件,用 const 引用傳,比如 const std::string&。

填空點一個填進空格,再點空格可以拿回來

選一個符號填進空格,讓 add_one 改到呼叫者的 count,程式顯示 6。

1#include <iostream>2 3void add_one(int n) {4    n = n + 1;5}6 7int main() {8    int count = 5;9    add_one(count);10    std::cout << count << '\n';11    return 0;12}
練習 3

修好它:引用不用寫 &

這段程式還帶著 C 的習慣,編譯不過。改好它,讓它顯示 a=8 b=5。

要顯示
a=8 b=5
exercise3.cpp
1#include <iostream>2 3void swap_values(int& a, int& b) {4    int t = a;5    a = b;6    b = t;7}8 9int main() {10    int a = 5;11    int b = 8;12    swap_values(&a, &b);13    std::cout << "a=" << a << " b=" << b << '\n';14    return 0;15}
輸出
點「執行」或按 Ctrl+Enter

還有這些不一樣

CC++
(double)xstatic_cast<double>(x),一眼就看得出是轉換
函式不能同名引數不同就能同名(過載,第 9 課)
#define MAX 100const int max_count = 100;,有型別
變數常寫在開頭用到時再宣告,for (int i = 0; ...)
malloc 的結果直接賦給 int*C++ 裡要轉換,編譯不過;所以更不該用 malloc

C++17 起還有更多(比如 std::string_view),這門課只用 C++14。

單選

C 的強制轉換 (double)x,在 C++ 裡推薦怎麼寫?

這一課學會了

  • printf 換成 std::cout:不用格式符,型別不會配錯;小數位和寬度用 <iomanip>。
  • char[] 和 strcpy / strcat / strcmp 換成 std::string 的 =、+、==;size() 不算 '\0'。
  • 陣列加長度換成 std::vector,傳參用 const std::vector<T>&。
  • malloc / free 換成 vector 和 std::unique_ptr,記憶體自己還;C++ 裡別用 malloc。
  • struct 不用 typedef;NULL 換成 nullptr;bool 是內建的。
  • 要改呼叫者的變數,傳引用,不傳指標;C 的標頭檔寫成 <cstdio>、<cmath>。
第 29 課學完了嗎?第 29 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 30 課 · 25 分鐘小專案:圖書借閱把學過的東西用在一起:寫一個小小的圖書借閱程式。Book 類、用 vector 放書架、用 map 記誰借了什麼,一步一步加上借書、還書、查詢。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。