#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");
}
Run Code Online (Sandbox Code Playgroud)
请编译这个,你只需要阅读getTI()和pop()方法.在运算符<<重载中,我们看到s.getTI的不同值,这很奇怪!
o<<"index("<<s.getTI()<<")= "<<s.pop()<<endl; //getTI prints 1.
Run Code Online (Sandbox Code Playgroud)
您假设s.getTI()之前已经过评估s.pop(),这不一定是真的.这些操作数的评估顺序是完全未指定的,事实上,我通常看到的模式大致是从右到左的评估.
执行s.getTI()和s.pop()评估的单独的代码行.