为什么这个自动存储结构仍然存在?
Why does this automatic-storage structure still exist?
代码
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()
是重要的块。
上面的代码应该用 Item
填充堆栈。当弹出 Item
时,它的 payment
被添加到 运行 total
.
此外,Stack
方法 pop()
和 push()
与 main()
中的函数进行区分。
困境
代码完全符合我的要求,但我不明白为什么...
我在 push()
函数中创建了一个本地 Item
。它被引用并放置在 Stack
上。但是,当push()
函数结束时,这个本地的Item
是自动存储的,不应该被删除吗?然而,不知何故它仍然存在,因为当我调用 pop()
时,它就在那里。
表达式items[top] = item
使用copy赋值运算符复制结构。
代码
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()
是重要的块。
上面的代码应该用 Item
填充堆栈。当弹出 Item
时,它的 payment
被添加到 运行 total
.
此外,Stack
方法 pop()
和 push()
与 main()
中的函数进行区分。
困境
代码完全符合我的要求,但我不明白为什么...
我在 push()
函数中创建了一个本地 Item
。它被引用并放置在 Stack
上。但是,当push()
函数结束时,这个本地的Item
是自动存储的,不应该被删除吗?然而,不知何故它仍然存在,因为当我调用 pop()
时,它就在那里。
表达式items[top] = item
使用copy赋值运算符复制结构。