C++学习日记之动态内存分配构建stack类

来源:互联网 发布:玩dnf老是网络中断 编辑:程序博客网 时间:2024/05/29 00:31
        本文基于动态内存分配的知识,使用类构建stack类,并同时编写复制构造函数与复制运算符
代码如下:
stack.h
#ifndef STACK_H_#define STACK_H_typedef unsigned long Item;#include<iostream>using std::ostream;class Stack{private:enum{MAX = 4};Item * pitems;int size;int top;public:Stack(int n= MAX);Stack(const Stack & st);~Stack();bool isempty() const;bool isfull() const;bool push(const Item & item);bool pop(Item & item);Stack & operator = (const Stack &st);friend ostream & operator << (ostream &os,const Stack &st);};#endif


stack.cpp
#include "stack.h"#include<iostream>Stack::Stack(int n){pitems = new Item[n];size = n;top=0;}Stack::Stack(const Stack &st){pitems = new Item [st.size];top = st.top;for(int i =0;i<top;i++)pitems[i]=st.pitems[i];size = st.size;}Stack::~Stack(){delete [] pitems;pitems=0;} bool Stack::isempty() const{return top==0;} bool Stack::isfull() const { return top==size; } bool Stack::push(const Item & item) { if(isfull()) return false; pitems[top++]=item; return true; } bool Stack::pop(Item & item) { if(isempty()) return false; item =pitems[--top]; return true; } Stack &Stack::operator = (const Stack & st) { delete [] pitems; pitems = new Item[st.size]; top=st.top; for(int i=0;i<top;i++) pitems[i]=st.pitems[i]; size=st.size; return *this; }ostream & operator << (ostream &os ,const Stack &st) { for(int i=0;i<st.top;i++) { os << st.pitems[i] <<  "    " ; } os << std::endl; return os; }


main.cpp
#include<iostream>#include"stack.h"int main(){Stack stack1(2);Stack stack2;Item a=3,b=4,c=5;stack1.push(a);stack1.push(b);stack1.push(5);stack2.push(8);Stack stack3(stack1);Stack stack4;stack4=stack1;Item item;stack1.pop(item);std::cout << item << std::endl;std::cout << stack1;std::cout << stack2;std::cout << stack3;std::cout << stack4;return 0;}


运行结果如下:
0 0
原创粉丝点击