C ++-将一个ostream中的数据发送到另一个ostream [英] C++ - Send data in one ostream to another ostream
问题描述
我不明白此ostream函数声明的含义:
I don't understand what this ostream function declaration means:
ostream& operator<< (ostream& (*pf)(ostream&));
(特别是(*pf)(ostream&)
部分).我想做类似的事情:
(specifically, the (*pf)(ostream&)
part). I want to do something like:
void print(ostream& os){
cout << os;
}
但是我得到了错误:
Invalid operands to binary expression ('ostream' . . . and 'ostream')
推荐答案
我不明白此ostream函数声明的含义:
I don't understand what this ostream function declaration means:
ostream& operator<< (ostream& (*pf)(ostream&));
您是否看到过std::endl
,std::flush
,std::hex
,std::dec
,std::setw
...之类的功能?都可以使用<<"将它们全部发送"到流中,然后使用流作为函数参数来调用它们,并对流进行魔术处理.它们实际上与上面的ostream& (*pf)(ostream&)
参数匹配,并且该运算符是允许使用它们的那个.如果我们看一下Visual C ++实现...
Have you seen functions like std::endl
, std::flush
, std::hex
, std::dec
, std::setw
...? They can all be "sent" to a stream using "<<", then they get called with the stream as a function argument and do their magic on the stream. They actually match the ostream& (*pf)(ostream&)
argument above, and that operator's the one that lets them be used. If we look at the Visual C++ implementation...
_Myt& operator<<(_Myt& (__cdecl *_Pfn)(_Myt&))
{
return ((*_Pfn)(*this));
}
...您可以看到是否只是调用函数,并将其用作参数的流传递.期望这些函数返回对相同流参数的引用,以便可以进一步链接<<
操作,或者可以将该流隐式转换为bool
,以测试流状态.
...you can see if just calls the function, passing the stream it's used on as an argument. The functions are expected to return a reference to the same stream argument, so that further <<
operations may be chained, or the stream may be implicitly converted to bool
as a test of stream state.
请参见 http://en.cppreference.com/w/cpp/io/manip 有关io机械手的更多信息.
See http://en.cppreference.com/w/cpp/io/manip for more information about io manipulators.
您需要帮助:
void print(ostream& os){
cout << os;
}
这里的问题是,您正在将ostream
参数发送到另一个流-cout
-并且它不知道您希望它如何处理.
The issue here is that you're sending the ostream
argument to another stream - cout
- and it doesn't know what you want it to do with it.
要将os
的当前内容发送到cout
,请尝试:
To send the current content of os
to cout
, try:
void print(ostream& os){
cout << os.rdbuf();
}
或者如果您要将一些实际数据打印到参数表示的流中:
Or if you want to print some actual data to the stream represented by the argument:
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`
这篇关于C ++-将一个ostream中的数据发送到另一个ostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!