Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

c++ - Why does omission of "#include <string>" only sometimes cause compilation failures?

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>.

So do I have to write #include <string> so that the code works?

question from:https://stackoverflow.com/questions/9539650/why-does-omission-of-include-string-only-sometimes-cause-compilation-failur

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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.

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).

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.

For instance, the following code compiles with my compiler (gcc 4.6):

#include <iostream>

int main() {
    std::string str;
}

But if I remove the first line, it no longer compiles even though the iostream header should actually be unrelated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...