C++: The order of std::cout

C++: The order of std::cout

本文关键字:std cout of order The C++      更新时间:2023-10-16

在这里,我编写了一个简单的队列类模板:

#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,(即如果firstnull),请使用它

也就是说,函数参数的求值顺序是未指定的(编译器可以按照任何顺序求值参数,只要它们都在函数本身启动之前完成)。也就是说,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从左到右取值。