0

我有一个 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
4

1 回答 1

1

尝试使用引用而不是复制对象。
在类型之后添加&以使用引用。

void run_stack_op(Stack& stack, string token) {

于 2015-09-25T01:43:15.623 回答