【12.4】c++ primer plus 课后编程答案

来源:互联网 发布:com口测试软件 编辑:程序博客网 时间:2024/06/07 02:18
C++ PRIMER PLUS 课后答案 使用IDE为window7系统下的VS2010
/*user.h*/#ifndef USERSH_H_#define USERSH_H_#include <string>using std::ostream;using std::istream;typedef unsigned long Item;class Stack{private:enum {MAX = 10};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);int showtop()const;int showpop()const;};#endif


/*userfucntion.cpp*/#include "usersh.h"#include <iostream>#include <cstring>#include <cctype>using std::cout;using std::cin;using std::ostream;using std::istream;Stack::Stack(int n /* = MAX */){if(n>MAX)n=MAX;size=n;pitems = new Item [size];top=0;}Stack::Stack(const Stack & st){size=st.size;pitems = new Item [size];for (int i=0;i<size;i++)pitems[i]=st.pitems[i];top=st.top;}Stack::~Stack(){delete [] pitems;}bool Stack::isempty()const{return top==0;}bool Stack::isfull()const{return top==size;}Stack & Stack::operator  =(const Stack & st){if(this==&st)return * this;delete [] pitems;size=st.size;pitems = new Item [size];for (int i=0;i<size;i++)pitems[i]=st.pitems[i];top=st.top;return * this;}bool Stack :: push(const Item & item){if (top<size){pitems[top++]=item;return true;}elsereturn false;}bool Stack::pop(Item & item){if (top>0){item = pitems[--top];return true;}elsereturn false;}int Stack::showtop()const{return top;}int Stack::showpop()const{return pitems[top];}

/*main*/#include <iostream>#include <Windows.h>#include "usersh.h"#include <cstdlib>#include <ctime>using std::cout;using std::cin;using std::endl;int main(){   int i=0;unsigned long Po;Stack s1(5);Stack s2(s1);Stack s3=s1;Stack s4(3);s4=s1;for (;i<20;i++){if (!s1.isfull()){cin>>Po;s1.push(Po);cout<<"s1 top:"<<s1.showtop()<<endl;}elsebreak;}cout<<endl;for(i=0;i<20;i++){if (!s1.isempty()){s1.pop(Po);cout<<s1.showpop()<<" has pop"<<endl;cout<<"s1 top:"<<s1.showtop()<<endl;}elsebreak;}system("pause");return 0;}


原创粉丝点击