1

I have the following struct and class definition that I'm having an issue with:

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;
    }
};

I run the following code in main:

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;
}

Why doesn't the sum add up to 12? I specified push constructor to be: void push(customer &c). The output from the code is:

10
Cash status: $3
Cash status: $5

Should the value in the stack be updated when I update c2.payment to 10?

4

2 回答 2

1

您通过引用传递参数,但您在下面的分配是将引用的对象复制到堆栈中。

堆栈[顶部++]=c;

这是使用隐式生成的赋值运算符,它复制客户类的每个成员。

于 2013-03-20T18:43:04.487 回答
0

在将 c2 添加到堆栈之前,您需要更改它的值。

于 2013-03-20T19:02:13.143 回答