请实现一个队列,既可以存放整数,又可以存放字符串。简单的说,队列是一种数据结构,按照先进先出的顺序管理进、出队列的元素。本题要求完成:
(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<<"整数:"<};
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<<"字符串:"<};
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;
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;
}
}
}
声明:
(一)由于考试政策等各方面情况的不断调整与变化,本网站所提供的考试信息仅供参考,请以权威部门公布的正式信息为准。
(二)本网站在文章内容来源出处标注为其他平台的稿件均为转载稿,免费转载出于非商业性学习目的,版权归原作者所有。如您对内容、版权等问题存在异议请与本站联系,我们会及时进行处理解决。
相关推荐
2023年4月山东自考宪法学考点:其他设立宪法法院的国家
03-132023年4月山东自考刑法学名词解释:特殊身份
03-132023年4月山东自考刑法学名词解释:战时临阵脱逃罪
03-132023年4月山东自考刑法学名词解释:冒充军人招摇撞骗罪
03-132023年4月山东自考刑法学名词解释:义务冲突
03-132023年4月山东自考刑法学名词解释:单位犯罪
03-132023年4月山东自考《经济法》复习资料(16)
03-142023年4月山东自考《经济法》复习资料(11)
03-142023年4月山东自考《文化政策与法规》章节讲义:第四章
03-152023年4月山东自考《秘书学概论》问答题总结(6)
03-16