c++ - 通用打印功能

标签 c++ operator-overloading iostream

我手头没有一本好的 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/

相关文章:

c++ - 将 vector<vector<char>> 转换为 vector<string>

c++ - STL 复制、对、 vector 和插入器

C++ Overload Operator = for Pointers 不能正常工作/编译

c++ - 如何从控制台读取空格分隔的数字?

c++ - 具有直接输出缓冲区/字符串结果访问的 std::stringstream,避免复制?

c++ - 将静态 C 库与 C++ 代码链接时出现 "undefined reference to"错误

c++ - 如何在使用 Eigen Library c++ 时删除特定行或列

c++ - SDL_Window 没有命名类型

c++ - 重载赋值运算符 C++

c++ - 递归函数中的cin