C++: The order of std::cout
C++: The order of std::cout
在这里,我编写了一个简单的队列类模板:
#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;
}
出现问题-输出为:
0
2
1
/*
Correct output should be:
1
1
2
*/
当我调试std::cout
行时,我发现程序首先调用最右边的bag.pop()
,然后调用另一个bag.pop()
,最后调用bag.get()
。这是正确的顺序吗?
T get() { //Get the first value of the Queue
return (!first) ? first->value : NULL;
};
这是倒退。放下!
。你说"如果first
是而不是非null,(即如果first
是null),请使用它
也就是说,函数参数的求值顺序是未指定的(编译器可以按照任何顺序求值参数,只要它们都在函数本身启动之前完成)。也就是说,get()
、pop()
和pop()
可以按任何顺序调用。将它们称为单独的声明:
int a = bag.get();
int b = bag.pop();
int c = bag.pop();
std::cout << a << b << c;
T get() { //Get the first value of the Queue
return (!first) ? first->value : NULL;
};
如果first
有效,则返回NULL
。这被解释为零。你应该颠倒你的逻辑。
是的,在计算参数的函数时未指定。通过这个简单的测试,你会明白这意味着什么。
#include <iostream>
int b(void) {std::cout<<3<<std::endl; return 3;}
int c(void) {std::cout<<4<<std::endl; return 4;}
int main(int argc, char *argv[])
{
int d = b() + c();
std::cout<<d<<std::endl;
return 0;
}
所以你会得到3 4 5或4 3 5。
首先看:http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
std::cout从左到右取值。
相关文章:
- std::cout.imbue()多重调用
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- std::cout输出int时出现编译错误
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- std::cout 来自多个线程
- 在 c++ 中以十六进制格式打印无符号字符(BYTE).使用 std::cout
- Cuda 基本程序 (将值写入矩阵和 std:cout 不起作用) ;主功能不启动
- 是否可以为 std::cout 创建别名?
- std::cout 在打印变量与函数表达式时的行为不同
- 带有 std::cout 的多线程控制台文本动画
- 捕获/禁止发送到 std::cout 的 OpenCV 警告
- printf() 和 std::cout 在指针方面的区别
- 使用字符串流加速 std::cout 日志记录
- 是否可以在每次使用std::cout时执行一个函数
- 为什么'std::cout << !+2 '输出 0?
- 如何将自定义类传递给std::cout
- 对于输出,std::copy是否比std::cout快