【问题标题】:why this unexpected variable change happens? [closed]为什么会发生这种意想不到的变量变化? [关闭]
【发布时间】:2013-01-18 22:31:14
【问题描述】:
        #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() 方法。在运算符

【问题讨论】:

  • 试着想出一个最小的例子,可能有十几行。

标签: c++ variables methods


【解决方案1】:
o<<"index("<<s.getTI()<<")= "<<s.pop()<<endl; //getTI prints 1.

您假设s.getTI()s.pop() 之前被评估,这不一定是真的。这些操作数的求值顺序完全没有指定,事实上,我通常看到的模式大致是从右到左的求值。

在不同的代码行上执行 s.getTI()s.pop() 评估。

【讨论】:

  • 是的,我已经在不同的行中尝试过,你是对的!但是为什么这些操作数的评估顺序是完全未指定的?是不是语言不通??
  • @user2038951:不,不是真的。语言没有理由定义操作数求值的顺序。您可以在需要时自己获得相同的结果,而当您不在乎时(大多数情况下),您无需为特权支付额外费用。
猜你喜欢
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
相关资源
最近更新 更多