我有一个Stack类,它在内部使用链表类list
。在我的main函数中,我的push和pop成员函数成功修改了给定的堆栈。我写了另一个函数,它接受一个堆栈并对它执行一些操作。在内部它使用推和弹。奇怪的是,这个函数内部似乎发生了变化,但在执行之后,堆栈保持不变。我将提供一些代码(如果需要,我可以添加更多代码):
void run_stack_op(Stack stack, string token) {
int operand1 = stack.pop();
int operand2 = stack.pop();
intfunc f = fmap[token];
cout << operand1 << ", " << operand2 << ", " << f(operand2, operand1) << endl;
stack.push(f(operand2, operand1));
cout << "current stack (in run_stack_op): " << stack.to_string() << endl;
}
...然后在主要:
s = Stack();
s.push(3); s.push(4);
run_stack_op(s, "-");
cout << "current stack (in main): " << s.to_string() << endl;
int val = s.pop();
cout << "should be -1: " << val << endl;
导致:
4, 3, -1
current stack (in run_stack_op): -1
current stack (in main): 4 3
should be -1: 4
答案 0 :(得分:1)
尝试使用引用而不是复制对象
在要使用引用的类型后添加&
。
void run_stack_op(Stack& stack, string token) {