问题描述
众所周知,用户可以这样定义流操纵符:
c> $ c> basic_ostream 类模板中的$ c>重载:
basic_ostream< charT ,traits>& operator< basic_ostream< charT,traits>&(* pf)(basic_ostream< charT,traits>&
参数是一个指向函数的指针,返回一个 std :: ostream 。
这意味着您可以将带有此签名的函数流式传输到 ostream 对象,它具有在流上调用该函数的效果。如果在表达式中使用函数的名称,那么它(通常)被转换为指向该函数的指针。
std :: hex 是 std :: ios_base 机械手,定义如下。
code> ios_base& hex(ios_base& 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>&) );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);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.
这篇关于流操纵器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!