//Apr 3
#ifndef _MO_STACK_
#define _MO_STACK_
#include
using namespace std;
class Item{
char _code[40];
int _quantity;
public:
Item(char* code="", int quantity=0);
friend ostream& operator<<(ostream& os, Item it);
};
class Node{
Item _data;
Node* next;
public:
Node(Item data, Node* Next);
friend class Stack;
};
class Stack{
Node* top;
public:
Stack();
~Stack();
void push(Item data);
Item pop();
bool IsEmpty();
};
#endif
//stack.cpp
//Apr 3
#include "stack.h"
#include
#include
using namespace std;
Node::Node(Item data, Node* Next){
this->_data=data;
this->next=Next;
}
Item::Item(char* code, int quantity){
strcpy(this->_code,code);
this->_quantity=quantity;
}
ostream& operator<<(ostream& os, Item it){
os<
}
Stack::Stack(){
top=(Node*)0;
}
bool Stack:: IsEmpty(){
return (!top);
}
void Stack::push(Item data){
top=new Node(data, top);
}
Item Stack::pop(){
Item item=top->_data;
Node* toDel=top;
top=top-> next;
delete toDel;
return item;
}
Stack::~Stack(){
while (!IsEmpty())
pop();
}
//stackMain.cpp
#include
using namespace std;
#include "stack.h"
int main(){
Stack s;
s.push(Item("muffin",2));
s.push(Item("puttin",10));
while(!(s.IsEmpty())){
cout<
getchar();
return 0;
}
Note: ' friend class Stack; ' is needed, otherwise when a stack object was created, the private data members , that is, '_data' and 'next' cannot be accessed.
Q: why in Stack::pop(), the return is 'Item' instead of 'Item&', I may figure it out later on.
No comments:
Post a Comment