cout <打印功能的调用顺序? [英] cout &lt;&lt; order of call to functions it prints?

查看:181
本文介绍了cout <打印功能的调用顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

  myQueue.enqueue('a'); 
myQueue.enqueue('b');
cout<< myQueue.dequeue()<< myQueue.dequeue();

打印ba到控制台



while:

  myQueue.enqueue('a'); 
myQueue.enqueue('b');
cout<< myQueue.dequeue();
cout<< myQueue.dequeue();

打印ab为什么是这样?



解决方案是什么?

似乎cout是最先调用最外层的函数<< 操作符没有序列点,因此编译器可以自由计算 dequeue 函数。可以保证的是,第二个 dequeue 调用的结果(按照它在表达式中出现的顺序,而不一定是它被求值的顺序)是 < 结果的第一个(如果你得到我的因此编译器可以自由地将你的代码转换成类似任何这样的东西(伪中间c ++)。这不是详尽的列表。

  auto tmp2 = myQueue.dequeue(); 
auto tmp1 = myQueue.dequeue();
std :: ostream& tmp3 = cout < tmp1;
tmp3<< tmp2;

  auto tmp1 = myQueue.dequeue(); 
auto tmp2 = myQueue.dequeue();
std :: ostream& tmp3 = cout < tmp1;
tmp3<< tmp2;

  auto tmp1 = myQueue.dequeue(); 
std :: ostream& tmp3 = cout < tmp1;
auto tmp2 = myQueue.dequeue();
tmp3<< tmp2;

这些是临时表达式在原始表达式中的对应。

  cout<< myQueue.dequeue()<< myQueue.dequeue(); 
| | | | |
| | ____ tmp1 _____ | | _____ tmp2 ____ |
| |
| ________ tmp3 _________ |


the following code:

myQueue.enqueue('a');
myQueue.enqueue('b');
cout << myQueue.dequeue() << myQueue.dequeue();

prints "ba" to the console

while:

myQueue.enqueue('a');
myQueue.enqueue('b');
cout << myQueue.dequeue();
cout << myQueue.dequeue();

prints "ab" why is this?

It seems as though cout is calling the outermost (closest to the ;) function first and working its way in, is that the way it behaves?

解决方案

There's no sequence point with the << operator so the compiler is free to evaluate either dequeue function first. What is guaranteed is that the result of the second dequeue call (in the order in which it appears in the expression and not necessarily the order in which it is evaluated) is <<'ed to the result of <<'ing the first (if you get what I'm saying).

So the compiler is free to translate your code into some thing like any of these (pseudo intermediate c++). This isn't intended to be an exhaustive list.

auto tmp2 = myQueue.dequeue();
auto tmp1 = myQueue.dequeue();
std::ostream& tmp3 = cout << tmp1;
tmp3 << tmp2;

or

auto tmp1 = myQueue.dequeue();
auto tmp2 = myQueue.dequeue();
std::ostream& tmp3 = cout << tmp1;
tmp3 << tmp2;

or

auto tmp1 = myQueue.dequeue();
std::ostream& tmp3 = cout << tmp1;
auto tmp2 = myQueue.dequeue();
tmp3 << tmp2;

Here's what the temporaries correspond to in the original expression.

cout << myQueue.dequeue() << myQueue.dequeue();
|       |               |    |               |
|       |____ tmp1 _____|    |_____ tmp2 ____|
|                       |
|________ tmp3 _________|

这篇关于cout <打印功能的调用顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆