C++ 程式可視為物件集合,透過呼叫彼此方法互動。核心概念:物件(狀態+行為)、類別(藍圖)、方法(行為實作)、即時變數(物件狀態)。
#include // 預處理指令:引入標頭檔
using namespace std; // 使用 std 命名空間
int main() { // 主函數:程式進入點
cout << "Hello World"; // 輸出
return 0; // 返回 0 表示成功
}
#include <iostream>:引入 I/O 流標頭檔,提供 cin/cout。using namespace std;:引入標準程式庫命名空間,簡化呼叫 (或用 std::cout 完全限定)。//:單行註解。int main():每個程式必須有一個,返回 int 給作業系統。cout << "...";:流插入運算子輸出至標準輸出。return 0;:正常結束。hello.cppg++ hello.cpp -o hello (生成可執行檔 hello 或 Windows hello.exe)./hello (Windows hello.exe)Hello World亦可使用 CMake、Makefile、IDE 建置系統管理大型專案。
;:陳述式終結符,邏輯實體結束標記。{...}:以大括號包裹的邏輯相關陳述式群組,形成新作用域。_ 組成。Manpower ≠ manpower。@, $, % 等)。mohd, zara, abc, move_name, a_123, myname50, _temp, j, a23b9, retVal不可作為標識符使用。C++17 共 84 個關鍵字 (含 alignas, constexpr, noexcept, thread_local 等新增):
alignas alignof asm auto bitand bitor bool break case catch char char16_t char32_t class compl const constexpr const_cast continue decltype default delete do double dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace new noexcept not not_eq nullptr operator or or_eq private protected public register reinterpret_cast return short signed sizeof static static_assert static_cast struct switch template this thread_local throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while xor xor_eq
三字元序列以 ?? 開頭,代表鍵盤無法輸入的字元 (歷史遺留):
| 三字元組 | 替換字元 |
|---|---|
??= | # |
??/ | \ |
??' | ^ |
??( | [ |
??) | ] |
??! | | |
??< | { |
??> | } |
??- | ~ |
現代編譯器預設關閉 (GCC 需 -trigraphs,MSVC 2010+ 預設關)。字串/字元常數中需連續兩個問號時,用字串連接 "...?" "?..." 或轉義 "...?\?..." 避免誤觸發。
int age; 中 int 與 age 間至少需一空白字元。fruit = apples + oranges; 運算子兩側空白非必須,但建議保留提升可讀性。