std::cout statements evaluation order(std::cout 语句评估顺序)
问题描述
pop() 函数有什么问题为什么不能正常工作?
What is wrong with the pop() function why doesn't it work correctly?
class stack{
int *p, *Cursor;
int size ;
public:
stack(int sz) {Cursor = p = new int[size=sz+1];} //consider the stack empty when its size is 1
~stack() {delete[] p;} //Cursor and P will be destroyed when the program finishes
void push(int x) {Cursor+=1; *Cursor=x; size++;}
int pop() {if(Cursor == p) return -1; int temp = *Cursor; Cursor--; size--; return (temp);}
bool isEmpty(){return(Cursor == p);}
bool isFull(){return(Cursor == p+size);}
};
这是我的测试:
stack A(3);
std::cout<<"Empty: "<<A.isEmpty()<<std::endl;
std::cout<<"Full: "<<A.isFull()<<std::endl;
A.push(10);
A.push(20);
A.push(30);
std::cout<<std::endl;
std::cout<<" 1st pop: "<<A.pop()<<std::endl<<" 2nd pop: " <<A.pop()<<std::endl<<" 3rd pop: " <<A.pop()<<std::endl<<" 4th pop: " <<A.pop()<<std::endl;
我得到的输出是:
1st pop: -1
2nd pop: 10
3rd pop: 20
4th pop: 30
虽然我应该得到这样的东西:
while I should get sth like:
1st pop: 30
2nd pop: 20
3rd pop: 10
4th pop: -1
问题是我哪里出错了?
推荐答案
没有出错,但是如果你把 pop
s (在你的情况下)从右到左计算,如果你把它们都放进去一个 std::cout
行.一般来说.评估顺序未指定.有关这方面的更多详细信息,请参阅此处.
Nothing did go wrong, but the pop
s get (in your case) evaluated from right to left if you put them all in one std::cout
line. In general. the evaluation order is unspecified. For more detail on this see here.
所以你正确地以插入的相反顺序获取元素,然后 -1
然后将它们反转打印.
So you correctly get the elements in reverse order of insertion and then -1
and then print them reversed.
这篇关于std::cout 语句评估顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::cout 语句评估顺序
基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01