本筆記整理自《C++ Primer Plus (6th Edition)》前四章核心知識點,適合快速回顧 C++ 基礎。
#include <iostream> 引入標準庫,C++ 標頭無 .h 後綴(C 標頭轉為 cxxx 形式,如 <cmath>)。using namespace std; 或 using std::cout; 避免污染全域。0 表成功,非零表失敗,回傳給作業系統。short ≥ 16bit, int ≥ short, long ≥ 32bit, long long ≥ 64bit。sizeof(int) 視平台而定。int a = 1;int b(2);int c{3}; 禁止縮窄轉換。wchar_t(寬字元)、char16_t/char32_t(C++11,UTF-16/32),字面值前綴 L/u/U。0 → false,非零 → true。float(≥32bit), double(≥48bit), long double。字面值預設 double,f 後綴指定 float。static_cast<T>(expr) 比 C 風格 (T)expr 更安全。auto x = 100; 推導為 int。int a[5]; 下標不檢查越界。sizeof(a) 為整個陣列位元組數(僅限定義作用域)。'\0' 結尾,strlen 不含結尾符。cin >> str 遇空白停止;getline 讀整行。+、==、size(),比字元陣列安全。R"(...) 內不轉義,自定界符 R"delim(...)delim"。struct Man { char name[20]; double weight; int age; };Man mike = {"Mike", 56.2, 22};(C++11 列表初始化)unsigned int x : 4; bool y : 1; 節省空間。enum Spectrum {red, orange, yellow}; 隱含 int,可指定值,取值範圍為能容納最大值的最小 2 的冪區間。& 取址,* 解引用。使用前必須初始化。new int; new int[10]; delete ptr; delete[] arr;。new 失敗拋 bad_alloc。ptr+1 前進一個元素大小(非位元組)。陣列名在多數語境下退化為首元素指標(右值)。#include <vector> vector<int> v(10); 動態陣列,自動管理記憶體,C++11 支援列表初始化。#include <array> array<int,5> arr; 固定大小、棧分配、效率同陣列但更安全。