#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 的不同值,这很奇怪!