为什么堆栈中的值甚至不更新,它是一个参考

Why doesn't the value in the stack update eventough its a reference

本文关键字:参考 一个 更新 堆栈 为什么      更新时间:2023-10-16

我有以下结构和类定义,我有一个问题:

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

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

为什么总和不是12?我指定push构造函数为:void push(customer &c)。代码的输出是:

10
Cash status: $3
Cash status: $5

当我更新c2时,堆栈中的值应该被更新吗?付款给10?

通过引用传递实参,但下面的赋值是将引用的对象复制到堆栈中。

堆栈(前+ +)= c;

这是使用隐式生成的赋值操作符,它复制customer类的每个成员。

在将c2加入堆栈之前,需要先修改c2的值