C++ 为什么';t堆栈更新事件中的值通过其引用
我对以下结构和类定义有疑问:C++ 为什么';t堆栈更新事件中的值通过其引用,c++,C++,我对以下结构和类定义有疑问: 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;
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;
}
};
当我将c2.payment更新为10时,堆栈中的值是否应该更新?您通过引用传递参数,但下面的赋值是将引用的对象复制到堆栈中 堆栈[top++]=c
这是使用隐式生成的赋值运算符,它复制customer类的每个成员。您通过引用传递参数,但下面的赋值是将引用的对象复制到堆栈中 堆栈[top++]=c
这是使用隐式生成的赋值运算符,它复制customer类的每个成员。在将c2添加到堆栈之前,需要更改c2的值。在将c2添加到堆栈之前,需要更改c2的值
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;
}
10
Cash status: $3
Cash status: $5