問題描述
以下代碼:
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<<調用它打印的函數的順序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!