我可以把ostream作为一个流吗?

时间:2016-11-18 16:46:05

标签: c++ types casting ofstream ostream

我有这段代码

heights

因为它说我需要使用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 } ofstream的内容打印到文件中,我可以将out转换为out并使用它吗?

例如,这会有效吗?

ofstream

这是主函数中调用此函数的代码

new_stream = (ofstream) out;

MyClass的类型为call_class 假设我不能只将参数cout << MyClass << endl; 更改为out

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

2 个答案:

答案 0 :(得分:1)

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

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

现在我们将输出到文件流。输出功能无关心输出的位置,您可以从呼叫站点控制输出功能。这也为您提供了相同的运算符适用于所有输出流的优势。我们可以将fout替换为cout,某些stringstream或来自ostream的任何其他流。

答案 1 :(得分:1)

正如所写的<?php $pages = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); $active = 1; $last = false; $next = false; if (isset($_GET['page'])) { $active = $_GET['page']; $last = $active - 1; $next = $active + 1; if (!in_array($next, $pages)) { $next = false; } if (($last < 0) or !in_array($last, $pages)) { $last = false; } } ?> <ul> <li> <a href="<?= $last != false ? '?page=' . $last : '' ?>"><- LAST</a> </li> <?php foreach ($pages as $page): ?> <li><a href="?page=<?= $page ?>"><?= $page ?> <?= $page == $active ? ' is active!' : ''?></a></li> <?php endforeach; ?> <li> <a href="<?= $next != false ? '?page=' . $next : '' ?>">NEXT -></a> </li> </ul> 的使用是正确和惯用的。要写入文件,只需创建类型为std::ostream的对象并将其用作流对象:

std::ofstream

这是有效的,因为call_class org = /* whatever */ std::ofstream str("myfile.txt"); str << org; 来自std::ofstream,因此您可以在预期引用std::ostream的任何地方传递std::ofstream。这是多态性的基础。

此外,如果仍然存在混淆,那同一个插入器可以与任何类型的std::ostream对象一起使用:

std::ostream
相关问题