问题描述
以下代码:
myQueue.enqueue('a');
myQueue.enqueue('b');
cout << myQueue.dequeue() << myQueue.dequeue();
在控制台打印ba"
同时:
myQueue.enqueue('a');
myQueue.enqueue('b');
cout << myQueue.dequeue();
cout << myQueue.dequeue();
打印ab"这是为什么?
prints "ab" why is this?
似乎 cout 首先调用最外层(最接近 ;)的函数并按其方式工作,这是它的行为方式吗?
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?
推荐答案
<<
运算符没有序列点,因此编译器可以自由地评估 dequeue
> 功能第一.保证的是第二个 dequeue
调用的结果(按照它在表达式中出现的顺序,不一定是它的计算顺序)是 <<
到 <<
的第一个结果(如果你明白我在说什么).
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).
因此编译器可以自由地将您的代码翻译成任何类似的东西(伪中间 C++).这并不是一份详尽的清单.
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;
或
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;
这是原始表达式中临时词对应的内容.
Here's what the temporaries correspond to in the original expression.
cout << myQueue.dequeue() << myQueue.dequeue();
| | | | |
| |____ tmp1 _____| |_____ tmp2 ____|
| |
|________ tmp3 _________|
这篇关于cout<<调用它打印的函数的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!