我不明白这个 ostream 函数声明的含义:
ostream& operator<< (ostream& (*pf)(ostream&));
你见过类似的函数吗std::endl
, std::flush
, std::hex
, std::dec
, std::setw
...?它们都可以使用“ostream& (*pf)(ostream&)上面的参数,并且该运算符是允许使用它们的运算符。如果我们看一下 Visual C++ 实现...
_Myt& operator<<(_Myt& (__cdecl *_Pfn)(_Myt&))
{
return ((*_Pfn)(*this));
}
...您可以看到是否只是调用该函数,并传递它所使用的流作为参数。这些函数预计返回对同一流参数的引用,以便进一步<<
操作可以是链接的,或者流可以隐式转换为bool
作为流状态的测试。
See http://en.cppreference.com/w/cpp/io/manip有关 io 操纵器的更多信息。
您需要以下方面的帮助:
void print(ostream& os){
cout << os;
}
这里的问题是您要发送ostream
另一个流的参数 -cout
- 它不知道你想用它做什么。
发送当前content of os
to cout
, try:
void print(ostream& os){
cout << os.rdbuf();
}
或者,如果您想将一些实际数据打印到参数表示的流中:
void print(ostream& os){
os << "show this!\n";
}
print(std::cout); // to write "show this!\n" to `std::cout`
print(std::cerr); // to write "show this!\n" to `std::cerr`