【问题标题】:Member functions change object from main but not from other function成员函数从主函数更改对象,但不从其他函数更改对象
【发布时间】:2015-09-25 01:41:52
【问题描述】:

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

...然后在 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

【问题讨论】:

    标签: c++ encapsulation member-functions mutability


    【解决方案1】:

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

    void run_stack_op(Stack&amp; stack, string token) {

    【讨论】:

    • 这会导致以下错误:/main.o: In function 'main': /homes/dwashburn/cs245/Workspace/Stack-C++/Debug/../main.cc:98: undefined reference to 'run_stack_op(Stack, std::string)' collect2: error: ld returned 1 exit status
    • 请同时修改原型声明。
    • 啊,呃。谢谢你。我会在允许的时候接受你的回答。
    猜你喜欢
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多