首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 基本語法完整指南:程式結構、編譯執行、標識符、關鍵字、三字元組與空白字元

     編輯:C++ 入門

C++ 基本語法完整指南:程式結構、編譯執行、標識符、關鍵字與詞法細節

C++ 程式可視為物件集合,透過呼叫彼此方法互動。核心概念:物件(狀態+行為)、類別(藍圖)、方法(行為實作)、即時變數(物件狀態)。

最小 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;:正常結束。

編譯與執行流程

  1. 編寫原始碼 → 儲存為 hello.cpp
  2. 編譯:g++ hello.cpp -o hello (生成可執行檔 hello 或 Windows hello.exe)
  3. 執行:./hello (Windows hello.exe)
  4. 輸出:Hello World

亦可使用 CMake、Makefile、IDE 建置系統管理大型專案。

分號與區塊

  • 分號 ;:陳述式終結符,邏輯實體結束標記。
  • 區塊 {...}:以大括號包裹的邏輯相關陳述式群組,形成新作用域。
  • C++ 不以換行作為陳述式結束,可將多陳述式寫在同一行 (不建議)。

C++ 標識符命名規則

  • 由字母 (A-Z, a-z)、數字 (0-9)、底線 _ 組成。
  • 首字元必須為字母或底線。
  • 大小寫敏感:Manpower ≠ manpower。
  • 不可包含標點符號 (@, $, % 等)。
  • 合法範例:mohd, zara, abc, move_name, a_123, myname50, _temp, j, a23b9, retVal

C++ 關鍵字 (保留字)

不可作為標識符使用。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; 運算子兩側空白非必須,但建議保留提升可讀性。
  • 純空白行 (含註解) 編譯器忽略。

總結

  • 掌握最小程式結構、編譯執行指令、分號區塊規則。
  • 遵循標識符命名規範,避開關鍵字。
  • 理解三字元組歷史背景,現代環境可忽略 (確保編譯器關閉)。
  • 善用空白字元排版,提升程式碼可讀性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved