c++ - 我可以将 ostream 转换为 ofstream 吗?

标签 c++ types casting ofstream ostream

我有这个代码

ostream & operator<<(ostream & out, call_class & Org)
{
    for (int i = 0; i<Org.count; i++)
    {
        out << Org.call_DB[i].firstname << "  " << Org.call_DB[i].lastname
            << "  " << Org.call_DB[i].relays << "  " << Org.call_DB[i].cell_number
            << "  " << Org.call_DB[i].call_length << endl;
    }

    //Put code to OPEN and CLOSE an ofstream and print to the file "stats7_output.txt".


    return out;  //must have this statement
}

正如它所说,我需要使用 ofstreamout 的内容打印到文件中,我可以将 out 转换为ofstream 并使用它?

例如,这行得通吗?

new_stream = (ofstream) out;

这是调用这个函数的main函数中的代码

cout << MyClass << endl;

MyClass 的类型是 call_class 假设我不能只将参数 out 更改为 ofstream

类型

编辑:谢谢大家的帮助。我知道由于缺乏明确的指导,这是一个很难回答的问题。我的教授基本上给了我们同一个问题的两个不同版本,但不清楚他在问什么。我只是将数据写入函数外部的文件,希望这足够好。

最佳答案

您误解了此运算符的工作原理。由于该函数采用 ostream &,因此它可以与派生自 ostream 的任何类一起使用,例如 ofstream。这意味着我们需要做的就是在 ofstream 实例上调用此函数,输出将定向到该实例引用的文件。看起来像

std::ofstream fout("some text file.txt");
call_class Org;
// populate Org
fout << Org;

现在我们将输出到文件流。输出函数不关心它输出到哪里,您可以从调用站点控制它。这也为您提供了同一个运算符处理所有输出流的优势。我们可以将 fout 替换为 cout、一些 stringstream 或从 ostream 派生的任何其他流。

关于c++ - 我可以将 ostream 转换为 ofstream 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40682183/

相关文章:

c++ - 从 sockaddr * 转换为 sockaddr_in * 增加了所需的对齐方式

c# - 通过 SWIG 到 C# 使用多个 dll

c++ - 默认的Visual Studio C++控制台应用程序有409个错误

generics - 如何将值映射到 Rust 中的类型?

javascript - StrictNullChecks 与通过语法的联合类型

c# - 'result is T' 与 'typeof(T).IsInstanceOfType(result)' 之间有显着差异吗?

C++:不能 static_cast 从 double* 到 int*

c++ - 将 C++ 接口(interface)实例化为子类

c++ - 使用 C++ 检测美式英语或英式英语拼写是否合适