錯誤現場
using namespace std;
#include <iostream> // 僅包含 iostream
template <class T>
class tree_node_t {
public:
string &to_string(string *result, int prefix = 0); // 錯誤:string 未宣告
void set_data(const T &data);
protected:
T m_data;
};
VS 編譯通過,g++ 卻噴 `error: 'string' is not a type`。
根本原因
- VS (MSVC) 寬鬆策略:`` 內部間接引入了 `` 的部分宣告,加上預編譯標頭機制,讓 `std::string` 在未顯式 `#include ` 時也能用。
- g++ (GCC/Clang) 嚴格遵循標準:C++ 標準規定必須顯式包含 `` 才能使用 `std::string`,`` 不保證引入它。
修正方法
#include <iostream>
#include <string> // 必須顯式加入
using namespace std;
// ... 後續程式碼
最佳實務:標頭檔自給自足
- 每個 `.cpp` / `.h` 只依賴自己直接使用的標頭檔,不要仰賴傳遞性包含。
- 啟用編譯器警告:`-Wmissing-include-dirs`、`-std=c++17 -pedantic`,提早暴露缺漏。
- 跨平台專案建議用 CMake `target_link_libraries` 管理依賴,避免手動維護包含路徑。
補充:為什麼 VS 不報錯?
MSVC 的標準庫實現中,`` 為了支援 `operator<<` 輸出 `std::string`,內部確實 `#include `。但這是實現細節,**不可攜帶**,換編譯器、換標準庫版本都可能斷崖式報錯。