简体   繁体   中英

Why does this automatic-storage structure still exist?

Code

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;
}

Remark

Most of main() is probably irrelevant, but I just want to show what I'm doing. push() and pop() are the important blocks.

The code above is supposed to fill a stack with Item s. When an Item is popped, its payment is added to a running total .

Also, differentiate between Stack methods pop() and push() with the functions in main() .


Dilemma

The code works exactly as I want it to, but I don't understand why...

I create a local Item in the push() function. It is referenced and placed onto the Stack . However, when the push() function ends, shouldn't this local Item be removed since it is on automatic storage? Yet, somehow it still exists because when I call pop() , there it is.

表达式items[top] = item使用复制分配运算符复制结构。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM