| 時代 | 頭文件 | 符號位置 | 狀態 |
| 早期 C++ (pre-1998) | iostream.h, fstream.h | 全域命名空間 | 已棄用,編譯器仍支援 |
| 標準 C++ (1998~) | iostream, fstream, vector... | namespace std | 現代標準 |
| C 標準庫 (C++ 相容) | stdio.h, stdlib.h | 全域 | 持續支援 |
| C 標準庫 (C++ 版) | cstdio, cstdlib | std:: (標準規定) | 現代用法 |
為何保留舊庫?
避免海量既有程式碼遷移成本。編譯器廠商承諾長期支援 .h 版 C++ 頭文件,但**標準委員會明確不推薦**使用。
實務:正確使用標準庫
#include <iostream> // 無 .h
#include <string>
#include <vector>
int main() {
using namespace std; // 在函數內部 using,限制污染範圍
string s; int age;
cin >> s >> age;
cout << s << " 成立 " << age << " 年了!" << endl;
return 0;
}
using namespace std; 的作用域策略
- **函數內部**(推薦):污染範圍最小。
- **全域**:方便但增加命名衝突風險,中大型專案**不推薦**。
- **精確引入**:
using std::cout; using std::cin; 僅引入所需符號。
- **完全限定**:
std::cout << std::endl; 最安全、最明確,無任何衝突可能。
cstdio 等 C++ 版 C 庫的雙重身分
標準規定符號在 std::,但主流編譯器(MSVC、GCC、Clang)**同時**注入全域命名空間以相容既有碼:
#include <cstdio>
// 兩種寫法在主流編譯器皆通過
std::printf("標準寫法\n");
printf("非標準但通用寫法\n");
建議:堅持 std::printf,保證跨平台、跨編譯器、未來版本相容。
總結
- 新代碼**一律使用無
.h 的標準頭文件**(iostream, vector, string...)。
- 符號位於
namespace std,採用函數級 using 或完全限定名。
- C 庫優先用
cstdio 等 c 前綴版,配合 std::。
- 拒絕
iostream.h 等舊式 C++ 頭文件,雖編譯器仍支援但非標準。
- 上一篇文章: C++ 輸入輸出流(cin/cout)全攻略:告別 scanf/printf 的優雅之道
- 下一篇文章: C++ 命名空間完整指南
Copyright ©
程式碼之家 All Rights Reserved