为什么cout返回smanip?

发布于 2024-10-11 03:47:31 字数 218 浏览 0 评论 0原文

谁能解释一下 setw 操纵器的声明?我试图理解它时完全被震惊了。! iomanip 中 setw 的声明如下

 smanip setw(int)

现在 smanip 是什么?当我们给出 std::cout << 时会发生什么setw(10)<< “Hai” [我想知道 setw 实际上如何影响输出,换句话说,在幕后发生的操作)

Could anyone explain me the declaration of the setw manipulator? I was completely blown off trying to understand it.! The declaration of the setw in iomanip is as follows

 smanip setw(int)

now what is 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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尬尬 2024-10-18 03:47:31

smanip 是实现定义的类型。只要工作完成,库就可以将其定义或 typedef 为任何它喜欢的内容。

实际上,它将是某种结构,表示(a)要执行的操作,以及(b)要在该操作中使用的参数10。它也可能有一个执行操作的函数,也可能没有,具体取决于实现如何定义operator<<(ostream &, smanip),或一些类似的重载来捕获必要的操作数类型。我还没有检查我的实现来找出答案。

至于输出如何受到影响:my_stream << setw(10) 被定义为对流具有与调用 my_stream.width(10) 相同的效果。因此,operator<< 重载将确保以某种特定于实现的方式发生。非参数化流操纵器的运算符重载是专门为调用操纵器而定义的,但使用 smanip 实现有更多的自由度。

smanip is an implementation-defined type. 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. 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. 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). So the operator<< overload will ensure that happens in some implementation-specific way. 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.

清醇 2024-10-18 03:47:31

setw(int) 本身不会修改任何内容。它只是返回一个流操纵器(smanip),可用于修改流的行为。

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

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

setw(int) by itself doesn't modify anything. It simply returns a stream manipulator (smanip) that can be used to modify the stream's behaviour.

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

int main () {
  cout << setw (10);
  cout << 77 << endl;
  return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文