为什么我需要包含iostream和fstream头来打开一个文件 [英] Why do I need to include both the iostream and fstream headers to open a file
问题描述
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("test.txt");
return 0;
}
fstream是从iostream派生的,为什么我们应该在上面的代码中包含?
fstream is derived from iostream, why should we include both in the code above?
我删除了fstream,但是,withstream有一个错误。我的问题是ofstream是从ostream派生的,为什么需要fstream来编译?
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?
推荐答案
$ c> fstream ,因为这是 ofstream
类的定义。
You need to include fstream
because that's where the definition of the ofstream
class is.
你有一种向后的感觉:因为 ofstream
源于 ostream
,所以 fstream
头包括 iostream
头,所以你可以省略 iostream
,它仍然会编译。但是你不能省略 fstream
,因为你没有 ofstream
的定义。
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
.
这样想。如果我把它放在 ah
:
Think about it this way. If I put this in a.h
:
class A {
public:
A();
foo();
};
然后我创建一个从 A
bh
:
#include <a.h>
class B : public A {
public:
B();
bar();
};
然后我想写这个程序:
int main()
{
B b;
b.bar();
return 0;
}
我需要包含哪个文件? b.h
。我如何只包括 ah
并期望有 B
?的定义?
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
?
请记住,在C和C ++中, include
是字面值。它字面上粘贴包含 include
语句的包含文件的内容。这不是一个更高层次的给我在这个班上的一切的声明。
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".
这篇关于为什么我需要包含iostream和fstream头来打开一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!