C++:std::cout 的顺序

标签 c++

<分区>

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

#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;
};

这是倒退的。放下 !。你是说“如果 firstnot 非空,(即如果 first null),使用它.

也就是说,函数参数的求值顺序是未指定的(编译器可以按照自己认为的任何顺序求值参数,只要它们都在函数本身启动之前完成)。即get()pop()pop() 可以按任意顺序调用。将它们称为单独的语句:

int a = bag.get();
int b = bag.pop();
int c = bag.pop();
std::cout << a << b << c;

关于C++:std::cout 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20123196/

相关文章:

c++ - 当我想扩展当前应用程序的功能时的 DIAMOND 情况

c++ - 此类代码中 gcc 和 clang 之间的不同行为

c++ - 操作重载 << 作为链表中的 friend

c++ - 将 std::vector<boost::shared_ptr<T>> 转换为 std::vector<T*> 的优雅解决方案

C++Builder Clang std::less 找不到重载的运算符<

c++ - vector 作为函数中的参数

c++ - [] 在 C++ 中的奇怪用法。怎么了?

c++ - 编译时单例多次实例化检测

c++ - 在字符串上使用 open (unix)

c++ - const 关键字在函数声明中的位置