Is this code correct?
#include <iostream> using namespace std; int main() { string s = "hello\n"; cout << s; }
hello
#include <iostream> using namespace std; int main() { string s = "hello\n"; cout << s; }
hello
The code is not correct. A std::string
was declared,
but there is no #include <string>
. But, still, it compiled. ☹
operator<<
cout << s;
. This meaning of <<
isn’t
built into C++ like integer addition. Instead, somebody must have
written a operator<<
function that takes an ostream
and a
std::string
.
<iostream>
and <string>
.
ostream
and string
.
<iostream>
, then <iostream>
has to #include <string>
.
<string>
, then <string>
has to #include <iostream>
.
#include <iostream> using namespace std; int main() { string s = "hello\n"; cout << s; }
hello
<iostream>
includes <string>
.
<string>
might include <iostream>
.
You can construct <iostream>
& <string>
so they don’t
#include
each other:
<iostream>: #define IOSTREAM_INCLUDED #ifdef STRING_INCLUDED #include <iostream-string-overloads> #endif <string>: #define STRING_INCLUDED #ifdef IOSTREAM_INCLUDED #include <iostream-string-overloads> #endif <iostream-string-overloads>: std::ostream &operator<<(std::ostream &, const std::string &);
#include <iostream> #include <string> using namespace std; int main() { string s = "hello\n"; cout << s; }
hello
#include
what you need.