流操纵器如何工作? [英] How do the stream manipulators work?
问题描述
众所周知,用户可以这样定义流操纵符:
ostream& tab(ostream& output)
{
返回输出<< '\t';
}
这可以在 main例如:
cout<<'a'<< tab<<'b'< c'
请解释一下这一切如何工作?如果运算符<< 假定作为第二个参数,指向接受并返回 ostream& 的函数的指针,那么请解释一下为什么它是必要的?如果函数不接受并返回 ostream& 但是 void 而不是 ostream& ,会出错什么?
此外,有趣的是,为什么dec,hex操纵器生效,直到我不在它们之间更改,但用户定义的操纵器应该总是使用为了 c> $ c> basic_ostream 类模板中的$ c>重载
: basic_ostream< charT ,traits>& operator< <(
basic_ostream< charT,traits>&(* pf)(basic_ostream< charT,traits>&
效果:无。不会作为格式化的输出函数(如第27.6.2.5.1节所述)。
返回:
pf(* this)
。
参数是一个指向函数的指针,返回一个 std :: ostream
。
这意味着您可以将带有此签名的函数流式传输到 ostream
对象,它具有在流上调用该函数的效果。如果在表达式中使用函数的名称,那么它(通常)被转换为指向该函数的指针。
std :: hex
是 std :: ios_base
机械手,定义如下。
code> ios_base& hex(ios_base& str);
效果:调用
str.setf(ios_base :: hex,ios_base :: basefield)
。
返回:str。
这意味着流 hex
到 ostream
将设置输出基本格式化标志以十六进制输出数字。机械手本身不输出任何东西。
It is well known that the user can define stream manipulators like this:
ostream& tab(ostream & output)
{
return output<< '\t';
}
And this can be used in main() like this:
cout<<'a'<<tab<<'b'<<'c'<<endl;
Please explain me how does this all work? If operator<< assumes as a second parameter a pointer to the function that takes and returns ostream &, then please explain my why it is necessary? What would be wrong if the function does not take and return ostream & but it was void instead of ostream &?
Also it is interesting why "dec", "hex" manipulators take effect until I don’t change between them, but user defined manipulators should be always used in order to take effect for each streaming?
The standard defines the following operator<<
overload in the basic_ostream
class template:
basic_ostream<charT,traits>& operator<<(
basic_ostream<charT,traits>& (*pf) (basic_ostream<charT,traits>&) );
Effects: None. Does not behave as a formatted output function (as described in 27.6.2.5.1).
Returns:
pf(*this)
.
The parameter is a pointer to a function taking an returning a reference to a std::ostream
.
This means that you can "stream" a function with this signature to an ostream
object and it has the effect of calling that function on the stream. If you use the name of a function in an expression then it is (usually) converted to a pointer to that function.
std::hex
is an std::ios_base
manipulator defined as follows.
ios_base& hex(ios_base& str);
Effects: Calls
str.setf(ios_base::hex, ios_base::basefield)
.Returns: str.
This means that streaming hex
to an ostream
will set the output base formatting flags to output numbers in hexadecimal. The manipulator doesn't output anything itself.
这篇关于流操纵器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!