Do I have to use #include beside ?

后端 未结 2 1328
时光说笑
时光说笑 2020-11-29 06:23

I started learning C++ and I read a book which writes that I must use the header file because the string type is not built directly into the comp

相关标签:
2条回答
  • 2020-11-29 07:04

    Do I have to include the <string> header when I want to use the string type if I included the <iostream> header?

    Yes, you have to. You cannot rely on relevant headers (e.g. <string>) being #included indirectly through other headers (e.g. <iostream>), although this might be the case on some implementations.

    And even when this may seem to work, it could lead to troubles if not all of the relevant overloads of some operators are imported, or if a class is forward-declared in a header you #include, but information on that class being derived from some other class is only contained in a header that does not get #included.

    See, for instance, this Q&A on StackOverflow for an example of such situations.

    0 讨论(0)
  • 2020-11-29 07:07

    Yes, you have to include what you use. It's not mandated that standard headers include one another (with a few exceptions IIRC). It might work now, but might fail on a different compiler.

    In your case, apparently <iostream> includes <string>, directly or indirectly, but don't rely on it.

    0 讨论(0)
提交回复
热议问题