为什么堆栈中的值甚至不更新,它是一个参考
Why doesn't the value in the stack update eventough its a reference
我有以下结构和类定义,我有一个问题:
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的值
相关文章:
- 在决定是通过参考还是通过价值时,尺寸真的是一个问题吗
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 是否有必要使用 std::move?这不是已经是一个右值参考了吗?
- 在VSCode中编译C++给了我一个未定义的参考
- 我对C++程序有一个未定义的参考,不知道如何处理它
- 调用gluPerspective和gluLookAt给了我一个不确定的参考
- 为什么要拿参考的地址给我一个第二等级的指针
- 为什么``polymorphic_allocator`取一个emore _ resource`指针''而不是参考
- 常量参考延长对象的寿命,然后是const_cast,这是一个好主意吗?
- 从指针参考C 创建一个新对象
- 一种体面的方式来转换const列表参考参数,然后传递到另一个函数
- 如果我创建一个模板类,而不是其他我将参考(指针)发送到该类的类
- 声明模板会员参考另一个类的模板成员数组
- 我已经创建了一个精灵的否,并以相同的参考将它们添加到场景中,现在,如何使用标签删除它们
- 查找从列表到一个参考列表的最接近点
- 参考数据会在const函数中更改另一个数据成员
- 第一个C 库:我不确定在哪里参考并声明我的变量
- 我是否做了一个悬置的参考
- 传递参考与价值:Java是一个混合体吗
- 休斯顿,我们有一个未定义的参考