C++中的ostream和ofstream转换

13

我的代码中有一个ostream对象,它由各个模块累积,并最终显示在控制台上。我还想将这个ostream对象写入文件,但是我必须使用一个ofstream对象重新编写所有代码吗?或者是否有一种方法将其转换为另一个对象(例如通过stringstream)?

例如,我的许多现有函数看起来像:

ostream& ClassObject::output(ostream& os) const
{
    os << "Details";
    return os;
}

如果我使用一个ofstream对象作为参数调用这个函数,那么这个ofstream对象是否可以积累信息?


4
“我可以使用 ofstream 对象调用这个函数吗?” 是的。ofstream 继承自 ostream,因此您可以直接将 ofstream 传递给该函数。 - Drew Dormann
2个回答

18

是的,你可以。这就是面向对象概念中所谓的子类型多态性的要点。由于ofstream派生自ostream,每个ofstream实例同时也是一个ostream实例(在概念上)。因此,你可以在任何需要ostream实例的地方使用它。


0

ofstream 派生自 ostream

只需在 main.cpp 中添加一些代码即可

#include "ClassObject"
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
     ClassObject ob;
     cout << ob; // print info to console window

     // save info to .txt file
     ofstream fileout;
     fileout.open("filename.txt", ios::app);
     fileout << ob;
     fileout.close();

     return 0;
}

希望这对你有用! - Binh Duong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接