語法書 / AA 競程語法書 下冊 / 第十三單元 / 結構體變數的初始化

13.3 結構體變數的初始化

13.2 的「宣告完再逐成員指派」要寫四行。跟 int x = 5; 一樣,結構體也能宣告時就初始化:大括號裡照成員宣告的順序把值列出來:

#include <iostream>
#include <string>
using namespace std;

struct student {
    string name;
    int seat;
    string phone;
};

int main() {
    student s = {"temmie", 60, "0912345678"};   // 照成員宣告的順序,一次填好
    cout << s.name << ' ' << s.seat << ' ' << s.phone << '\n';

    student t = {"bob"};        // 只給了第一個成員
    cout << t.seat << '\n';     // 沒給到的成員自動補「零」:int 是 0、string 是空字串
    return 0;
}

執行結果:

temmie 60 0912345678
0

三條規則:

  1. 順序照成員宣告的順序。寫錯位置時,型態對不上會直接編譯錯誤(60 塞給 string 成員會得到 could not convert '60' from 'int' to 'std::string');但如果錯位的兩個成員剛好同型態,編譯器抓不到,資料就悄悄錯位——大括號裡欄位一多,自己多看一眼。
  2. 沒給到的成員自動補「零」——跟上冊 6.5 陣列初始化「沒給到的自動補 0」是同一條規則。student u = {}; 就是「全部歸零」的慣用寫法。
  3. 這套大括號跟 6.5 陣列的 {1, 2, 3}10.11 pair 的 {3, 5} 是同一家人。結構體陣列也能用——外層是陣列的大括號、內層是每一包的:
student a[2] = {{"alice", 5, "0911111111"}, {"bob", 7, "0922222222"}};

動手試試看:先猜 student u = {"cathy", 3};(沒給電話)三個成員各是什麼,寫程式驗證;再故意把 60 放到大括號的第一格,看看編譯器的錯誤訊息長什麼樣。