为什么会发生这种意外的变量变化

why this unexpected variable change happens?

本文关键字:意外 变量 变化 为什么      更新时间:2023-10-16
        #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()计算。