C ++:std :: cout的顺序 [英] C++: The order of std::cout
问题描述
这里,我写了一个简单的队列类模板:
Here, I wrote a simple Queue Class Template:
#include "stdafx.h"
#include "iostream"
#include "conio.h"
template <class T> class Queue {
private:
struct Node {
T value;
Node *next;
};
Node *first, *last;
public:
Queue () { //Initialization
first = 0;
last = 0;
};
void push(T value) { //Put new value into Queue
Node *p = new Node;
p->value = value;
if (!first) //If Queue is not empty
first = p;
else
last->next = p;
last = p; //Put the value to the last of the Queue
};
T get() { //Get the first value of the Queue
return (first) ? first->value : NULL;
};
T pop() { //Take the first value out of Queue
T result = first->value;
Node *temp = first;
first = first->next;
delete temp;
return result;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
Queue<int> bag;
bag.push(1); //Bag has value 1
bag.push(2); //Bag has values: 1, 2
std::cout << bag.get() << '\n' << bag.pop() << '\n' << bag.pop();
_getch();
return 0;
}
有一个问题 - 输出为:
There is a problem - the output is:
0
2
1
/*
Correct output should be:
1
1
2
*/
std :: cout
行,我发现程序调用 bag.pop()
在最右边,那么另一个 bag.pop()
,最后是 bag.get()
。
When I debug the std::cout
line, I found out that program call bag.pop()
at the right most first, then the other bag.pop()
, at last the bag.get()
.
Is that the right order?
解决方案
推荐答案
/获取队列的第一个值
return(!first)? first-> value:NULL;
};
T get() { //Get the first value of the Queue
return (!first) ? first->value : NULL;
};
这是向后的。删除!
。你是说如果第一
是不非空,(即如果第一
This is backwards. Drop the !
. You are saying "if first
is not non-null, (ie if first
is null), use it.
也就是说,函数参数的求值顺序是未指定的(编译器可以评估函数的参数这是 get()
, pop()
和 pop()
可以按任何顺序调用它们作为单独的语句调用:
That said, the order of evaluation of arguments to a function is unspecified (the compiler can evaluate the arguments in any order it feels like, as long as they are all done before the function itself starts). That is get()
, pop()
and pop()
can be called in any order. Call them as separate statements:
int a = bag.get();
int b = bag.pop();
int c = bag.pop();
std::cout << a << b << c;
这篇关于C ++:std :: cout的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!