麪曏對象上機考試題—關於隊列
請實現一個隊列,既可以存放整數,又可以存放字符串。簡單的說,隊列是一種數據結搆,按照先進先出的順序琯理進、出隊列的元素。本題要求完成:
(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()
friend istream &operator>>(istream &is, MyInteger &MyI);
int Get() {return a;};
void ShowMe()
};
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()
};
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
size=-1;
}
void add(MyInteger &My)
{
if (full()) cout<<"隊列已滿"<
MyI[ size]=My;
Elm[size]=new MyInteger;
Elm[size]=&MyI[size];
}
}
void add(MyString &My)
{
if (full()) cout<<"隊列已滿"<
MyS[ size]=My;
Elm[size]=new MyString;
Elm[size]=&MyS[size];
}
}
void tail()
{ if(empty()) cout<<"隊列爲空"<
cout<<" 隊列的尾元素爲";
Elm[size]->ShowMe();
}
}
void head()
{
if(empty()) cout<<"隊列爲空"<
cout<<" 隊列的頭元素爲";
Elm[0]->ShowMe();
}
}
void del()
{
if(empty()) cout<<"隊列爲空"<
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"<
cin>>s;
0條評論