問題描述
我是 C++ 的初學者.當我編寫代碼時,有時我會寫 #include
并且代碼有效,有時我不寫 #include
并且代碼沒有不行.但有時它可以在沒有 #include
的情況下工作.
I am a beginner with C++. When I write the code sometimes I write #include <string>
and the code works, other times I don't write #include <string>
and the code doesn't work. But sometimes it works without #include <string>
.
那么我是否必須編寫 #include <string>
才能使代碼有效?
So do I have to write #include <string>
so that the code works?
推薦答案
如果您使用在標準標頭 string
內聲明的成員,那么是的,您必須直接或間接包含該標頭(通過其他標題).
If you use members that are declared inside the standard header string
then yes, you have to include that header either directly or indirectly (via other headers).
某些 編譯器在 some 平臺上可能會在每月的 某些 時間編譯,即使您沒有包含頭文件.這種行為令人遺憾、不可靠,并不意味著您不應包含標題.
Some compilers on some platforms may on some time of the month compile even though you failed to include the header. This behaviour is unfortunate, unreliable and does not mean that you shouldn’t include the header.
原因很簡單,您包含了其他標準標題,也恰好包含string
.但正如我所說,這通常不能依賴,它也可能會突然發(fā)生變化(例如,當安裝了新版本的編譯器時).
The reason is simply that you have included other standard headers which also happen to include string
. But as I said, this can in general not be relied on and it may also change very suddenly (when a new version of the compiler is installed, for instance).
始終包含所有必要的標題.不幸的是,似乎沒有可靠的在線文檔來說明需要包含哪些標題.查閱一本書或官方的 C++ 標準.
Always include all necessary headers. Unfortunately, there does not appear to be a reliable online documentation on which headers need to be included. Consult a book, or the official C++ standard.
例如,以下代碼使用我的編譯器 (gcc
4.6) 進行編譯:
For instance, the following code compiles with my compiler (gcc
4.6):
#include <iostream>
int main() {
std::string str;
}
但是如果我刪除第一行,即使 iostream
標頭實際上應該是無關的,它也不再編譯.
But if I remove the first line, it no longer compiles even though the iostream
header should actually be unrelated.
這篇關于為什么省略“#include <string>"?只是有時會導致編譯失敗?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!