面向对象上机考试题—关于堆栈(续)
//建立一个栈类,能够存放图形元素(矩形或圆形),有入栈,出栈。
//取栈顶的功能。建立元素类,里面至少一个纯虚函数,矩形和圆形类。
//来实现里面的函数SHOWME,实现他的显示图形信息的功能。重载>>.
//能够输入图形信息。测试以上类的功能。
#include "stdafx.h"
#include "iostream.h"
#include "string.h"
const n=50;
class shape
{
protected:
double width, length;
public:
shape() {}
virtual void ShowMe()=0;
};
class rectangle:public shape
{
public:
rectangle():shape(){}
friend istream &operator>>(istream &is, rectangle &rec)
{
cout<<"请输入长方形的长:";
is>>rec.length;
cout<<"请输入长方形的宽:";
is>>rec.width;
return is;
}
void ShowMe()
{
cout<<"长方形的长宽分别为:("<<length
<<","<<width<<")"<<endl;
}
};
class circle:public shape
{
private:
//double x, y;
double r;
public:
circle():shape(){r=0;}
friend istream &operator>>(istream &is, circle &cir)
{
cout<<"请输入圆的圆心坐标(x,y):";
is>>cir.width;
is>>cir.length;
cout<<"请输入圆的半径:";
is>>cir.r;
return is;
}
void ShowMe()
{
cout<<"圆的圆心坐标为:("<<width<<","<<length<<")"
<<" 半径为:"<<r<<endl;
}
};
class stack
{
shape *sp[n];
rectangle rec[n];
circle cir[n];
int size;
public:
stack()
{
for (int i=0; i<n; i++)
sp[i]=NULL;
size=-1;
}
bool empty(){return size==-1;}
bool full(){return size==n-1;}
void push(rectangle &rect)
{
rec[++size]=rect;
sp[size]=new rectangle;
sp[size]=&rec[size];
}
void push(circle &circ)
{
cir[++size]=circ;
sp[size]=new circle;
sp[size]=&cir[size];
}
void top()
{
if (empty()) cout<<"栈为空"<<endl;
else {
cout<<"栈顶元素为:"<<endl;
sp[size]->ShowMe();
}
}
void pop()
{
if (empty()) cout<<"栈为空"<<endl;
else {
cout<<"出栈元素为:"<<endl;
sp[size--]->ShowMe();
}
}
};
void main()
{
stack Stack;
rectangle rec;
circle cir;
int s=1;
while (s)
{
cout<<endl;
cout<<"请选择1-5号键*作"<<endl;
cout<<" 1: 矩形进栈;"<<endl;
cout<<" 2: 圆进栈;"<<endl;
cout<<" 3: 显示栈顶元素;"<<endl;
cout<<" 4: 出栈;"<<endl;
cout<<" 5: 退出程序;"<<endl;
cin>>s;
switch(s)
{
case 1: cin>>rec; Stack.push(rec); break;
case 2: cin>>cir; Stack.push(cir); break;
case 3: Stack.top(); break;
case 4: Stack.pop(); break;
case 5: s=0; break;
//default: cout<<"请重新输入"<<endl; break;
}
}
}
- 热门课程
- 报名咨询
- 2022年10月自考西方政治制度知识点:宪政
- 2022年10月自考马克思主义哲学原理知识点:唯心主义和存在的根源
- 2022年10月自考马克思主义哲学原理知识点:马克思主义哲学的产生是哲学发展中的伟大变革
- 2022年10月自考马克思主义哲学原理知识点:唯物主义
- 2022年10月自考马克思主义哲学原理知识点:哲学与科学的分化
- 2022年10月自考马克思主义哲学原理知识点:马克思主义哲学的历史发展
- 2022年10月自考马克思主义哲学原理知识点:马克思主义哲学与中国的社会主义事业
- 2022年10月自考马克思主义哲学原理知识点:对世界统一性的不同认识
- 2022年10月自考马克思主义哲学原理知识点:意识是物质的产物
- 2022年10月自考马克思主义哲学原理知识点:意识的能动作用