我有这段代码
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
答案 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