成员函数从main函数更改对象,而不是从其他函数更改对象

Member functions change object from main but not from other function

本文关键字:函数 对象 其他 成员 main      更新时间:2023-10-16

我有一个Stack类,它在内部使用链表类list。在主函数中,push和pop成员函数成功地修改了给定的堆栈。我已经编写了另一个函数,它接受堆栈并对其执行一些操作。内部使用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;
}

…然后在main中:

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

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

void run_stack_op(Stack& stack, string token) {