首页>计算机>软件水平考试>模拟试题>正文
面向对象上机考试题(2)堆栈

www.zige365.com 2008-11-6 22:00:20 点击:发送给好友 和学友门交流一下 收藏到我的会员中心

1.请实现一个栈,既可以存放整数,又可以存放字符串。简单的说,栈是一种数据结构,按照后进先出的顺序管理进、出栈的元素。本题要求完成:
(1) 实现描述栈的类Stack,其中定义了栈的大小Size(即栈中可以存放的元素个数),并包括进栈函数Push,出栈函数Pop和显示栈顶元素的函数Top。
(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)
{ 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)
{ is>>MyS.s;
return is; }

class stack
{ MyString MyS[max];
MyInteger MyI[max];
int top;
public:
stack() {top=-1;}
void push(MyInteger &My)
{ MyI[++top]=My; }

void push(MyString &My)
{ MyS[++top]=My; }

void Top()
{
if (empty()) cout<<"栈为空"<else MyI[top].ShowMe();
}
void Tops()
{
if (empty()) cout<<"栈为空"<else MyS[top].ShowMe();
}

void pop()
{ MyI[top--].ShowMe(); }

void pops()
{ MyS[top--].ShowMe(); }

bool empty()
{ return (bool)(top==-1); }

bool full()
{ return (bool)(top==max-1); }
};

int main(int argc, char* argv[])
{ MyInteger My1;
MyString My2;
stack st1, st2;
int i, j;

cout<<"请输入要进栈整数个数:";
cin>>j;
cout<<"请输入"<for (i=0; i{ cin>>My1;
st1.push(My1);
}
cout<<"栈顶元素为:";
st1.Top();
cout<<"请输入要出栈的元素个数:";
cin>>j;
cout<<"依次出栈元素为:"<for (i=0; ist1.pop();
cout<<"出栈后栈顶元素为:";
st1.Top();
cout<<"请输入要进栈的字符串个数:";
cin>>j;
cout<<"请输入"<for (i=0; i{
cin>>My2;
st2.push(My2);
}
cout<<"栈顶元素为:";
st2.Tops();
cout<<"请输入要出栈的元素个数:";
cin>>j;
cout<<"依次出栈元素为:"<for (i=0; ist2.pops();
cout<<"出栈后栈顶元素为:";
st2.Tops();

return 0;
}

我要投稿 新闻来源: 编辑: 作者:
相关新闻
08年11月软考英语考前练习试题及答案汇总
08年11月软考英语考前练习试题及翻译(1)
08年11月软考英语考前练习及解析(18)
08年11月软考英语考前练习试题及解析(17)
08年11月软考英语考前练习试题及解析(16)
08年11月软考英语考前练习试题及解析(15)