Can std::string be used without #include <string>? [duplicate]

吃可爱长大的小学妹 提交于 2019-12-01 15:20:43

Your implementation's iostream header includes string. This is not something which you can or should rely on. If you want to use std::string, you should always #include <string>, otherwise your program might not run on different implementations, or even in later versions of your current one.

Some header might include other headers, but that's an implementation issue and not something you can count on. Always explicitly include the headers you need.

In short: yes, it is necessary.

Parts of standard library often use other parts, so <string> was included somehow through <iostream>, and your code compiles nicely.

If you accidentally decide that you don't need <iostream> anymore and remove that include, <string> will be implicitly removed, too, and you get a confusing compilation error. That's why it is a good practice to put all necessary includes.

iostream includes <string>. It ripples through.

Well actually that's implementation dependant and not a guarantee. You should explicitly include the headers you need.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!