在 Qt 專案(特別是舊版教程範例)編譯時,常遇到 error: 'xxx' is not a member of 'std' 錯誤。本文說明成因與兩種解決方式。
早期 C++ 標準庫實作(如 STLport、舊版 libstdc++)將部分型別定義於全域命名空間而非 std,或標頭檔包含關係不同。常見於:
std::size_t、std::ptrdiff_t、std::NULL 等offsetof 等)在原始檔最前面加入:
#include <cstddef> // 定義 size_t, ptrdiff_t, NULL, offsetof 等
<cstddef> 是 C++ 版 <stddef.h>,確保相關型別正確置於 std 命名空間。
std:: 前綴(快速修正)若確認型別確實存在於全域命名空間,可直接移除 std:::
// 錯誤
std::size_t len = 0;
// 修正
size_t len = 0;
#include <cstddef> 等標準 C++ 標頭檔(<stddef.h>。CONFIG += c++11(qmake)或 set(CMAKE_CXX_STANDARD 11)(CMake)。using namespace std; 污染全域命名空間,改用具體 using std::vector; 或完整限定名稱。namespace std { using ::size_t; } 注入(謹慎使用)。| C 標頭檔 | C++ 標頭檔 | 主要內容 |
|---|---|---|
<stddef.h> | <cstddef> | size_t, ptrdiff_t, NULL, offsetof |
<stdlib.h> | <cstdlib> | malloc, free, exit, atoi 等 |
<string.h> | <cstring> | memcpy, strlen, strcmp 等 |
<math.h> | <cmath> | sin, cos, sqrt 等 |