gpt4 book ai didi

c++ - 为什么我需要同时包含 iostream 和 fstream header 才能打开文件

转载 作者:IT老高 更新时间:2023-10-28 22:02:30 26 4
gpt4 key购买 nike

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

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

fstream 是从 iostream 派生的,为什么我们要在上面的代码中同时包含这两者?

我删除了 fstream,但是,ofstream 有一个错误。我的问题是 ofstream 是从 ostream 派生的,为什么需要 fstream 才能编译?

最佳答案

您需要包含 fstream 因为这是 ofstream 类的定义所在。

你有点倒过来:因为 ofstream 派生自 ostreamfstream header 包含 iostream header ,因此您可以省略 iostream 并且它仍然可以编译。但是您不能省略 fstream,因为那样您就没有 ofstream 的定义。

这样想。如果我把它放在 a.h:

class A {
public:
A();
foo();
};

然后我在 b.h 中创建一个派生自 A 的类:

#include <a.h>

class B : public A {
public:
B();
bar();
};

然后我想写这个程序:

int main()
{
B b;
b.bar();

return 0;
}

我必须包含哪个文件? b.h 显然。我怎么能只包含 a.h 并期望有一个 B 的定义?

请记住,在 C 和 C++ 中,include 是文字。它实际上将包含文件的内容粘贴到 include 语句所在的位置。这不像是“把这个类家族中的所有东西都给我”的更高级的声明。

关于c++ - 为什么我需要同时包含 iostream 和 fstream header 才能打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2451681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com