【问题标题】:Why does this automatic-storage structure still exist?为什么这种自动存储结构仍然存在?
【发布时间】:2017-02-17 14:26:13
【问题描述】:

代码

stack.h:

struct customer
{
    char fullname[35];
    double payment;
};

typedef customer Item;

class Stack
{
private:
    ...
    Item items[MAX];
public:
    ...
    bool push(const Item & item);
    bool pop(Item & item);
};

main.cpp:

#include "stack.h"

...

int main()
{
    Stack s; double total;
    while (1)
    {
        ...
        cin >> c;
        switch (c)
        {
        case '1': push(s);
            break;
        case '2': pop(s, total);
            break;
        ...
        }
    }
    ...
}

void push(Stack & s)
{
    Item newitem;
    cout << "name -- ";    cin >> newitem.fullname;
    cout << "payment -- "; cin >> newitem.payment;
    s.push(newitem);
}

void pop(Stack & s, double & total)
{
    Item olditem;
    s.pop(olditem);
    total += olditem.payment;
}

备注

main() 的大部分内容可能无关紧要,但我只想展示我在做什么。 push()pop() 是重要的块。

上面的代码应该用Items 填充堆栈。当一个Item 被弹出时,它的payment 被添加到一个正在运行的total

另外,使用main() 中的函数区分Stack 方法pop()push()


困境

代码完全按照我的意愿运行,但我不明白为什么......

我在push() 函数中创建了一个本地Item。它被引用并放置在Stack 上。但是,当push()函数结束时,这个本地Item不应该被删除,因为它是在自动存储上的吗?然而,不知何故它仍然存在,因为当我调用pop() 时,它就在那里。

【问题讨论】:

  • 也许 Stack 类中的 push() 代码会创建对象的副本并将该副本存储在 items 数组中
  • 如果你指的是Stack::push(),没有。它接受参数的地址。我有实现,它看起来不像是复制它:items[top] = item;
  • 你能说明Stack::pushStack::pop的定义吗?
  • 在我们走“发布这个”“现在发布那个”的道路之前,停止。请按照帮助中心的指示出示您的 minimal reproducible example
  • @Sir Jony,该行正在复制对象。此外,您的函数采用 const 引用,而不是地址。

标签: c++ stack automatic-storage


【解决方案1】:

表达式items[top] = item 使用copy 赋值运算符来复制结构。

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多