简体   繁体   中英

Why header string is required for cout?

Why in the below code without including "string" header I can declare string variable. But compiler complains only for cout, when I try to print the string.

What information "string" header consists of ?

  #include <iostream>
//#include "string"

int main () 
{
    std::string str="SomeWorld";

    std::cout<<str<<std::endl;

  return 0;
}

Because the header defining std::basic_string is most likely (indirectly) included by <iostream> ( std::string is a typedef based on std::basic_string<char> ). The overload for operator<< for std::cout however is only defined in <string> .

它不是std::cout所必需的,它是std::string必需的。

Strictly speaking, anything could happen unless you include all the correct headers. There is no mandatory inclusion of one standard header into any other. So to be portable and correct, you have to say this:

#include <string>    // for `std::string`
#include <ostream>   // for `std::ostream &` in `operator<<`
#include <iostream>  // for std::cout

int main() {
  std::string str = "hello world";
  std::cout << str << std::endl;
}

In any real implementation you can almost always get away with omitting some of the headers (eg ostream would probably have been included in iostream ), but the above is the standard-compliant way.

The <string> header includes the definition of the string class (note: #include "string" means to include the string file in the current directory, so you should use angle brackets instead of " for system includes.)

However, iostream already includes string , (for example, to declare the operator<< that works for std::string ) so this is why you don't need to include it in this case.

In any case, it is a good practice to include the headers you just need. This makes your code more portable, and more explicit in case you copy that code into another context, say, that don't include iostream as a previous include. Also, note that it is never specified that, for example, including iostream will make std::string available, so strictly speaking, you have to include string to use std::string .

Because <string> is included in <iostream> . That is why the compiler is not complaning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM