Why do I need to include both the iostream and fstream headers to open a file

三世轮回 提交于 2019-11-26 21:12:32

问题


#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("test.txt");
  return 0;
}

fstream is derived from iostream, why should we include both in the code above?

I removed fstream, however, there is an error with ofstream. My question is ofstream is derived from ostream, why fstream is needed to make it compile?


回答1:


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".




回答2:


std::ofstream is defined in the <fstream> standard library header.

You need to include that header for its definition so that you can instantiate it.




回答3:


The typedef ofstream and its associated class template are defined by #include <fstream> , so you need that header.

For your actual program, #include <iostream> is not needed. But you may wish to use your fstream object with some functions which operate on ostream or istreams .

Those functions are not defined by #include <fstream> and you need to include the right header for any functions you do use. Some implementations might cause #include <fstream> to also include <iostream> but this is not guaranteed by the C++ Standard.

For example, this code:

ofstream myfile;
myfile.open ("test.txt");

myfile << 1;

requires #include <ostream> (or , since C++11, #include <iostream> which is guaranteed to bring in #include <ostream>).



来源:https://stackoverflow.com/questions/2451681/why-do-i-need-to-include-both-the-iostream-and-fstream-headers-to-open-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!