面向對象上機考試題—關于隊列
請實現一個隊列,既可以存放整數,又可以存放字符串。簡單的說,隊列是一種數據結構,按照先進先出的順序管理進、出隊列的元素。本題要求完成:
(1) 實現描述隊列的類Queue,其中定義了隊列的大小Size(即隊列中可以存放的元素個數),并包括進隊列函數Add,出隊列函數Delete、顯示隊列頭部元素的函數Head和顯示隊列尾部元素的函數Tail.
(2) 定義基類Element,至少包含純虛函數ShowMe.
(3) 從基類Element中派生整數類MyInteger和字符串類MyString, 具體實現上述純虛函數ShowMe,顯示該元素的類型和相應的值。
(4) 重載輸入“>>”*作符,使得可以通過cin直接讀入上述整數類和字符串類的對象值。
(5) 編寫main函數,測試上述所要求的各種功能,即可以根據菜單命令增加隊列元素、刪除隊列元素、顯示隊列頭部元素和隊列尾部元素,其中的元素可以是整數和/或字符串。
提示:
虛擬基類Element的定義至少包括以下純虛函數ShowMe.
class Element
{
// ……
public:
virtual void ShowMe () = 0;
// ……
};
*/
#include "stdafx.h"
#include "iostream.h"
#include "string.h"
const max=1000;
#define NULL 0
class Element
{ public:
virtual void ShowMe () = 0;
};
class MyInteger:public Element
{ int a;
public:
MyInteger(){a=0;}
friend istream &operator>>(istream &is, MyInteger &MyI);
int Get() {return a;};
void ShowMe()
{ cout<<"整數:"<<a<<endl; }
};
istream &operator>>(istream &is, MyInteger &MyI)
{
cout<<" 請輸入整數:";
is>>MyI.a;
return is; }
class MyString:public Element
{ char s[100];
public:
friend istream &operator>>(istream &is, MyString &MyS);
void ShowMe()
{ cout<<"字符串:"<<s<<endl; }
};
istream &operator>>(istream &is, MyString &MyS)
{
cout<<" 請輸入字符串:";
is>>MyS.s;
return is;
}
class Queue
{ int size;
Element *Elm[max];
MyInteger MyI[max];
MyString MyS[max];
public:
Queue(){
for (int i=0; i<max; i++)
Elm[i]=NULL;
size=-1;
}
void add(MyInteger &My)
{
if (full()) cout<<"隊列已滿"<<endl;
else {
MyI[++size]=My;
Elm[size]=new MyInteger;
Elm[size]=&MyI[size];
}
}
void add(MyString &My)
{
if (full()) cout<<"隊列已滿"<<endl;
else {
MyS[++size]=My;
Elm[size]=new MyString;
Elm[size]=&MyS[size];
}
}
void tail()
{ if(empty()) cout<<"隊列為空"<<endl;
else{
cout<<" 隊列的尾元素為";
Elm[size]->ShowMe();
}
}
void head()
{
if(empty()) cout<<"隊列為空"<<endl;
else{
cout<<" 隊列的頭元素為";
Elm[0]->ShowMe();
}
}
void del()
{
if(empty()) cout<<"隊列為空"<<endl;
else{
cout<<" 出隊列的元素為";
Elm[size--]->ShowMe();
}
}
bool empty()
{
return (bool)(size==-1);
}
bool full()
{
return (bool)(size==max-1);
}
};
void main()
{ MyInteger my1;
MyString my2;
Queue queue;
int s=1;
while(s)
{
cout<<"Please select 1-6 "<<endl;
cout<<" 1: 整數進隊列;"<<endl;
cout<<" 2: 字符串進隊列;"<<endl;
cout<<" 3: 顯示隊列頭元素;"<<endl;
cout<<" 4: 顯示隊列尾元素"<<endl;
cout<<" 5: 出隊列;"<<endl;
cout<<" 6: 退出程序"<<endl;
cout<<"--------------------------------------"<<endl;
cout<<"請選擇您的*作:";
cin>>s;
switch(s)
{
case 1: cin>>my1; queue.add(my1); break;
case 2: cin>>my2; queue.add(my2); break;
case 3: queue.head(); break;
case 4: queue.tail(); break;
case 5: queue.del(); break;
default: s=0; break;
}
}
}
- 熱門課程
- 報名咨詢
- 2022年10月自考西方政治制度知識點:憲政
- 2022年10月自考馬克思主義哲學原理知識點:唯心主義和存在的根源
- 2022年10月自考馬克思主義哲學原理知識點:馬克思主義哲學的產生是哲學發展中的偉大變革
- 2022年10月自考馬克思主義哲學原理知識點:唯物主義
- 2022年10月自考馬克思主義哲學原理知識點:哲學與科學的分化
- 2022年10月自考馬克思主義哲學原理知識點:馬克思主義哲學的歷史發展
- 2022年10月自考馬克思主義哲學原理知識點:馬克思主義哲學與中國的社會主義事業
- 2022年10月自考馬克思主義哲學原理知識點:對世界統一性的不同認識
- 2022年10月自考馬克思主義哲學原理知識點:意識是物質的產物
- 2022年10月自考馬克思主義哲學原理知識點:意識的能動作用



