14.3 結構體變數的初始化
14.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;
}