多态应用实例一:几何形体程序
用基类指针数组存放派生类对象的指针地址,是多态的常用应用,遍历该指针数组就能对各个派生类对象做各种操作。
problem
输入不同几何形体及其参数,要求按照面积大小顺序输出其对应的面积,以及集合形体形状。
code
#include <iostream>
#include <math.h>
#include<stdlib.h>
using namespace std;
class CShape{
public:
virtual double Area() = 0;//纯虚函数
virtual void PrintInfo() = 0;
};
class CRectangle: public CShape{
public:
double l,w;
double Area(){
return l*w;
}
void PrintInfo(){
cout<<"Rectangle: "<<Area()<<endl;
}
};
class CTriangle: public CShape{
public:
double a,b,c;
double Area(){
double p = (a+b+c)/2.0;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
void PrintInfo(){
cout<<"Triangle: "<<Area()<<endl;
}
};
class CCircle: public CShape{
public:
double r;
double Area(){
return 3.14159*r*r;
}
void PrintInfo(){
cout<<"Circle: "<<Area()<<endl;
}
};
int comp(const void *s1,const void *s2){
CShape **p1;
CShape **p2;
p1 = (CShape **)s1;
p2 = (CShape **)s2;
double d1,d2;
d1 = (*p1)->Area();
d2 = (*p2)->Area();
return d1>d2?1:-1;
}
int main(){
CShape *pShapes[100];
int n;
cin>>n;
char c;
CRectangle *pr; CTriangle *pt; CCircle *pc;
for(int i=0;i<n;i++){
cin>>c;
switch(c){
case'R':
pr = new CRectangle();
cin>>pr->l>>pr->w;
pShapes[i] = pr;
break;
case'T':
pt = new CTriangle();
cin>>pt->a>>pt->b>>pt->c;
pShapes[i] = pt;
break;
case'C':
pc = new CCircle();
cin>>pc->r;
pShapes[i] = pc;
break;
default: break;
}
}
qsort(pShapes,n,sizeof(CShape *),comp);
for(int i=0;i<n;i++){
pShapes[i]->PrintInfo();
}
return 0;
}