gpt4 book ai didi

c++ - 流操纵器如何工作?

转载 作者:IT老高 更新时间:2023-10-28 21:50:47 26 4
gpt4 key购买 nike

众所周知,用户可以像这样定义流操纵器:

ostream& tab(ostream & output)
{
return output<< '\t';
}

这可以像这样在 main() 中使用:

cout<<'a'<<tab<<'b'<<'c'<<endl;

请解释一下这一切是如何工作的?如果 operator<< 假定第二个参数是指向接受并返回 ostream & 的函数的指针,那么请解释一下为什么它是必要的?如果函数不接受并返回 ostream & 但它是 void 而不是 ostream & 会有什么问题?

另外有趣的是,为什么“dec”、“hex”操纵器在我不更改它们之间才会生效,但应该始终使用用户定义的操纵器才能对每个流式传输生效?

最佳答案

该标准定义了以下 operator<< basic_ostream 中的过载类模板:

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).

参数是一个指向函数的指针,该函数获取和返回对 std::ostream 的引用。 .

这意味着您可以将具有此签名的函数“流式传输”到 ostream对象,它具有在流上调用该函数的效果。如果您在表达式中使用函数的名称,那么它(通常)会转换为指向该函数的指针。

std::hexstd::ios_base机械手定义如下。

   ios_base& hex(ios_base& str);

Effects: Calls str.setf(ios_base::hex, ios_base::basefield).

Returns: str.

这意味着流媒体 hexostream将输出基本格式标志设置为以十六进制输出数字。操纵器本身不输出任何内容。

关于c++ - 流操纵器如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4633864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com