为什么会发生这种意外的变量变化
why this unexpected variable change happens?
#include <iostream>
#include <fstream>
using namespace std;
const int maxsize=20;
class IntStack{
private:
int element[maxsize],topindex;
public:
IntStack(){topindex=-1;}
int getTI(){
return topindex;
}
int top(){
if(topindex==-1)
exit(-1);
return element[topindex];
}
int top(int *t){
if(topindex==-1)
return -1;
t=&element[topindex];
return 0;
}
int pop(){
if(topindex==-1)
exit(-1);
topindex--;
return element[topindex+1];
}
int pop(int *t){
if(topindex==-1)
return -1;
t=&element[topindex];
topindex--;
return 0;
}
int push(int e){
if(topindex==19)
return -1;
topindex++;
element[topindex]=e;
return 0;
}
inline int empty(){return topindex==-1;}
ostream& print(ostream& o){
for(int i=0;i<=topindex;i++){
o<<element[i]<<' ';
}
return o;
}
};
ostream& operator <<(ostream& o,IntStack s){ ostream& operator <<(ostream& o,IntStack &s)
cout<<s.getTI()<<endl; // prints 2
while(s.empty()==0){
o<<"index("<<s.getTI()<<")= "<<s.pop()<<endl; //getTI prints 1.
}
return o;
}
int main(){
IntStack s;
s.push(5);
s.push(6);
s.push(7);
cout<<s; // the indexes should be 2, 1 , 0 but they are 1 0 -1!
system("pause");
}
请编译它,你只需要阅读getTI()和pop()方法。 在重载<<运算符中,我们看到 s.getTI 的不同值,这很奇怪!
o<<"index("<<s.getTI()<<")= "<<s.pop()<<endl; //getTI prints 1.
你假设s.getTI()
是在s.pop()
之前被评估的,这不一定是真的。这些操作数的求值顺序是完全没有指定的,事实上,我通常看到的模式大致是从右到左求值。
在单独的代码行上执行s.getTI()
和s.pop()
计算。
相关文章:
- 变量的值何时可以在C++中意外更改?
- C++ std::valarray 成员变量意外更改
- 将 std::sort 与指向整数变量的指针一起使用会产生意外的输出
- 意外的静态计数器变量行为
- 条件变量的"wait"函数在提供谓词时导致意外行为
- 具有类构造函数和类成员变量的意外输出值
- 带有布尔转换的变量的原始打印:意外行为
- 变量的字节表示的意外结果
- 仅在标头中的外部变量意外工作,原因是什么
- 将指针传递到私有变量时出现意外行为
- 变量意外更改值
- 对变量范围感到困惑 - 析构函数意外调用
- 声明变量大小数组时出现意外的编译器行为
- 传递给函数的变量,提供意外值
- 为什么我的 C++ 类变量意外地在范围之外更改
- 返回递归函数的bool意外地更改了变量
- 对整型变量的双精度值-意外输出
- 对象的成员变量发生意外更改
- 模板类中的变量模板-意外错误(可能存在错误?)
- 在程序中使用非类型模板参数而未给局部变量赋值时,会导致意外结果