Why header string is required for cout?
Why in the below co开发者_开发百科de 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>
.
It's not required for std::cout
, it's required for 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 (e.g. 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.
精彩评论