我手头没有一本好的 C++ 书籍,谷歌也没有找到任何有用的东西。
这是如何运作的?从概念上讲,这里发生了什么?从技术上讲,operator<<() 的原型(prototype)是否已预定义,作者如何知道如何编写它以便 << 重载以输出 Container 值?
哪里可以看operator<<()
以便我可以重载它?
对于输入,您还需要一个开始和结束“位置”c.begin()
, c.end()
...但对于输出,您需要一个“位置”ostream_iterator
.这似乎有点不对称。
template <typename Container>
std::ostream& operator<<(std::ostream& os, const Container& c)
{
std::copy(c.begin(), c.end(),
std::ostream_iterator<typename Container::value_type>(os, " "));
return os;
}
最佳答案
这很模糊,但我会试一试:
Technically, is the prototype for operator<<() predefined, how did the writer of this know how to write it so that << is overloaded to output Container values?
Where can I go to look at the operator<<() so that I can overload it?
您可以为所有尚未重载的用户定义类型重载运算符。参见 here有关这方面的更多信息。
Also for an input you need a start and an end "place" c.begin(), c.end()...but for output you need one "place" ostream_iterator. This seems a bit asymmetrical.
以此为题...
这正是 std::copy()
的定义方式:它需要一个输入范围(由开始和结束迭代器定义)和一个用于写入位置的输出迭代器。它假设,无论它写到哪里,都有足够的空间。 (如果您采用输出流运算符,则总是有足够的空间。)
你可能想得到自己 a good C++ book .
关于c++ - 通用打印功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7942174/