2013-03-20 52 views
1

我有我有同一個問題,下面的結構和類定義:爲什麼沒有在棧更新值eventough其參考

struct customer{ 
    string fullname; 
    double payment; 
}; 

class Stack{ 
private: 
    int top; 
    customer stack[10]; 
    bool full; 
    double sum; 
public: 
    Stack(){ 
     top=0; 
     full=false; 
     double sum=0.0; 
    } 

    bool isFull(){ 
     return full; 
    } 

    void push(customer &c){ 
     if(!full) 
      stack[top++]=c; 
     else 
      cout << "Stack full!" << endl; 
    } 

    void pop(){ 
     if(top>0){ 
      sum+=stack[--top].payment; 
      cout << "Cash status: $" << sum << endl; 
     } 
     else 
      cout << "Stack empty!" << endl; 
    } 
}; 

我在主運行下面的代碼:

int main(){ 
    customer c1 = {"Herman", 2.0}; 
    customer c2 = {"Nisse", 3.0}; 
    Stack stack = Stack(); 
    stack.push(c1); 
    stack.push(c2); 
    c2.payment=10.0; 
    cout << c2.payment << endl; 
    stack.pop(); 
    stack.pop(); 
    return 0; 
} 

爲什麼總和不等於12?我指定推構造器是:void push(customer &c)。代碼的輸出是:

10 
Cash status: $3 
Cash status: $5 

當我更新c2.payment到10時,應該更新堆棧中的值嗎?

回答

1

通過引用傳遞參數,但下面的任務是將引用的對象複製到堆棧中。

stack [top ++] = c;

這是使用隱式生成的賦值運算符,它複製客戶類的每個成員。

0

您需要在將c2添加到堆棧之前更改c2的值。