You need to include fstream
because that's where the definition of the ofstream
class is.
You've kind of got this backwards: since ofstream
derives from ostream
, the fstream
header includes the iostream
header, so you could leave out iostream
and it would still compile. But you can't leave out fstream
because then you don't have a definition for ofstream
.
Think about it this way. If I put this in a.h
:
class A {
public:
A();
foo();
};
And then I make a class that derives from A
in b.h
:
#include <a.h>
class B : public A {
public:
B();
bar();
};
And then I want to write this program:
int main()
{
B b;
b.bar();
return 0;
}
Which file would I have to include? b.h
obviously. How could I include only a.h
and expect to have a definition for B
?
Remember that in C and C++, include
is literal. It literally pastes the contents of the included file where the include
statement was. It's not like a higher-level statement of "give me everything in this family of classes".
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…