CS253: Software Development with C++

Spring 2018

Implicit Inclusion

See this page as a slide show

CS253 Implicit Inclusion

Dubious Code

Is this code correct?

#include <iostream>

using namespace std;

int main() {
    string s = "hello\n";
    cout << s;
}
hello

Bad Code

#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<<

Light Dawns

#include <iostream>

using namespace std;

int main() {
    string s = "hello\n";
    cout << s;
}
hello

This Could Happen

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 &);

Solution

#include <iostream>
#include <string>

using namespace std;

int main() {
    string s = "hello\n";
    cout << s;
}
hello

Theoretical

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:53

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building