Stack.cpp
#include <iostream> using namespace std; typedef unsigned long Item; class Stack{ private: enum{MAX=10}; Item *pitems; int size; int top; public: Stack(int n=MAX) { pitems=new Item[MAX]; top=0;//从0开始 size=0; } Stack(const Stack &st) { //Stack(st.size);//委托构造,因为长度不同 //Item *p=pitems; pitems=new Item[st.size]; top=0;//从0开始 size=0; for(int i=0;i<st.size;i++) { pitems[i]=st.pitems[i]; size++; top++; } //size=st.size; //top=st.top; } ~Stack() { delete []pitems; } bool isEmpty() { return top==0; } bool isFull() { return top==MAX; } bool push(const Item &it) { if(isFull()) cout<<"error! Stack is full!"<<endl; else { pitems[top++]=it; size++; return true; } return false; } bool pop(Item &item) { if(isEmpty()) cout<<"error! Stack is empty!"<<endl; else { item=pitems[top--]; size--; return true; } return false; } Stack &operator=(const Stack &st) { return Stack(st);//委托构造 } friend ostream&operator<<(ostream &os,const Stack &st)//方便检测 { os<<"This Stack is:"<<endl; int len=st.top-1; while(len!=-1)//从top开始呈现 { cout<<st.pitems[len]<<endl; len--; } //cout<<endl; return os; } };;
main124.cpp
#include <iostream> #include "Stack.cpp" using namespace std; void main124() { Stack s; Item it[20]={0}; for(int i=0;i<11;i++) { it[i]=i+1; s.push(it[i]); } //s.push(it[10]); //s.pop(it[0]); cout<<s; Stack s1(s); cout<<"s1="<<s1; Stack s2=s; cout<<s; cin.get(); }
——————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:https://www.royalchen.com/
author:royalchen
Email:royalchen@royalchen.com
———————————————————————————————————————————————————