简体   繁体   English

为什么cout返回smanip?

[英]Why does cout return smanip?

Could anyone explain me the declaration of the setw manipulator? 谁能解释一下setw机械手的声明? I was completely blown off trying to understand it.! 我完全不懂尝试。 The declaration of the setw in iomanip is as follows iomanip中setw的声明如下

 smanip setw(int)

now what is smanip? 现在什么是smanip? what happens when we give std::cout << setw(10) << "Hai" [ i want to know how the output is actually affected by setw, in other words the actions happening under the hood) 当我们给std :: cout << setw(10)<<“ Hai”时会发生什么[我想知道setw实际上如何影响输出,换句话说,在幕后发生的动作)

smanip is an implementation-defined type. smanip是实现定义的类型。 The library can define or typedef it to anything it likes, as long as the job gets done. 只要完成工作,该库就可以将其定义或键入定义为喜欢的任何东西。

In practice, it will be some kind of structure representing (a) the manipulation to be performed, and (b) the argument 10 to be used in this manipulation. 实际上,它将是某种结构,表示(a)要执行的操作,以及(b)在该操作中使用的参数10 It might also have a function to perform the manipulation, or it might not, depending how the implementation has defined operator<<(ostream &, smanip) , or some similar overload to catch the necessary operand types. 它可能还具有执行操作的功能,也可能没有,这取决于实现如何定义operator<<(ostream &, smanip)或某些类似的重载来捕获必要的操作数类型。 I haven't checked my implementation to find out. 我尚未检查实现以找出答案。

As for how the output is affected: my_stream << setw(10) is defined to have the same effect on the stream as calling my_stream.width(10) . 至于如何影响输出: my_stream << setw(10)被定义为对流具有与调用my_stream.width(10)相同的效果。 So the operator<< overload will ensure that happens in some implementation-specific way. 因此, operator<<重载将确保以某种特定于实现的方式发生这种情况。 The operator overload for non-parameterized stream manipulators is defined specifically to call the manipulator, but with smanip there's a little more freedom for implementations. 非参数化流操纵器的运算符重载专门定义为调用操纵器,但是使用smanip ,实现的自由度更高。

setw(int) by itself doesn't modify anything. setw(int)本身不会进行任何修改。 It simply returns a stream manipulator (smanip) that can be used to modify the stream's behaviour. 它只是返回一个流操纵器(smanip),可用于修改流的行为。

// setw example
#include <iostream>
#include <iomanip>
using namespace std;

int main () {
  cout << setw (10);
  cout << 77 << endl;
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM