首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ Primer 第五版:Code::Blocks 編譯空指標報錯原因與解決

     編輯:程式設計綜合問答

常見錯誤現象

程式碼:

int *p = nullptr; // 或 int *p = 0; / NULL
// 編譯錯誤:'nullptr' was not declared in this scope

根本原因

  • 編譯器預設標準為 C++98,不支援 C++11 的 nullptr。
  • Code::Blocks 預設使用 GCC,需手動開啟 -std=c++11 (或 c++14/c++17)。

解決步驟

  1. 選單 Settings → Compiler...
  2. 分頁 Compiler settings → Compiler flags(或 Global compiler settings)。
  3. 勾選 Have g++ follow the C++11 ISO C++ language standard [-std=c++11]。
    或手動在 Other compiler options 加入 -std=c++11 (建議 -std=c++17)。
  4. 按 OK,重新建置。

驗證程式碼

#include <iostream>
int main() {
    int *p = nullptr; // C++11
    if (!p) std::cout << "空指標\n";
    int *q = 0;       // C++98 相容
    int *r = NULL;    // 需 #include 
    return 0;
}

補充:Code::Blocks 專案建議設定

  • Compiler flags:-Wall -Wextra -pedantic -std=c++17
  • Debug 建置:加 -g;Release:加 -O2 -s。
  • 連結器:若用 C++17 filesystem,需加 -lstdc++fs (GCC < 9)。
  • 編碼:原始檔存為 UTF-8,終端機輸出中文需 SetConsoleOutputCP(65001) (Windows)。

參考資源

  • Code::Blocks 官方 Wiki:Compiler flags
  • C++ Primer 5th 範例碼編譯說明:通常附錄或 GitHub repo 有 CMakeLists.txt,建議改用 CMake + VS Code / CLion 更現代。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved