The Preprocessor in C++ (and in C) behaves by effectively copying the text of the referenced file into the file that used the #include
statement.
So when you write code like this:
Something.h
int my_rand() {
return 4; //chosen by dice roll, guaranteed to be fair
}
Main.cpp
#include "Something.h"
int main() {
return my_rand();
}
The final file before the proper compilation starts looks like this.
int my_rand() {
return 4; //chosen by dice roll, guaranteed to be fair
}
int main() {
return my_rand();
}
In your case, writing something like
class my_class {
#include<fstream>
/*...*/
};
Will result in some very strange behavior, and will almost certainly not compile, because the entire contents of <fstream>
will be copied into the middle of your class, and it's extremely unlikely that you've written your class in a way that will accomodate that, or that <fstream>
is written to handle being injected into a different class.
There are some cases where you can #include
in the middle of your program like that, however. Observe:
My Resource.txt
R"D(
Blah Blah Blah Blah Blah
)D"
Main.cpp
int main() {
std::string blah_string = "" //The "" is unnecessary, but I use it to make Intellisense shut up
#include "My Resource.txt"
;
std::cout << blah_string << std::endl;
return 0;
}
Which will correctly print out
Blah Blah Blah Blah Blah
To the console, because it's the same as writing
int main() {
std::string blah_string =
R"D(
Blah Blah Blah Blah Blah
)D"
;
std::cout << blah_string << std::endl;
return 0;
}