# 纯虚函数与基类指针数组的应用

10
5
2 4
1 2 3
4 3

#include<iostream>
using namespace std;
#define PI 3.14159
class Shape
{
public:
virtual void printName()=0;
virtual double printArea()=0;
};
class Circle:public Shape
{
double r;
public:
Circle(double r)
{
this->r=r;
}
virtual void printName()
{
cout<<"圆:"<<"半径="<<r<<",";
}
virtual double printArea()
{
return PI*r*r;
}
};
class Square:public Shape
{
double a;
public:
Square(double a)
{
this->a=a;
}
virtual void printName()
{
cout<<"正方形:"<<"边长="<<a<<",";
}
virtual double printArea()
{
return a*a;
}
};
class Rectangle:public Shape
{
double a,b;
public:
Rectangle(double a,double b)
{
this->a=a;
this->b=b;
}
virtual void printName()
{
cout<<"长方形:"<<"长="<<a<<","<<"宽="<<b<<",";
}
virtual double printArea()
{
return a*b;
}
};
class Trapezoid:public Shape
{
double m,n,h;
public:
Trapezoid(double m,double n,double h)
{
this->m=m;
this->n=n;
this->h=h;
}
virtual void printName()
{
cout<<"梯形:"<<"上底="<<m<<","<<"下底="<<n<<","<<"高="<<h<<",";
}
virtual double printArea()
{
return (m+n)*h/2;
}
};
class Triangle:public Shape
{
double m,h;
public:
Triangle(double m,double h)
{
this->m=m;
this->h=h;
}
virtual void printName()
{
cout<<"三角形:"<<"底边="<<m<<","<<"高="<<h<<",";
}
virtual double printArea()
{
return m*h/2;
}
};
int main()
{
double a1;
double b1;
double c1,c2;
double d1,d2,d3;
double e1,e2;
cin>>a1;
cin>>b1;
cin>>c1>>c2;
cin>>d1>>d2>>d3;
cin>>e1>>e2;

Shape *s[5];
Circle circle1(a1);
Square square1(b1);
Rectangle rele1(c1,c2);
Trapezoid td1(d1,d2,d3);
Triangle tre1(e1,e2);
s[0]=&circle1;
s[1]=&square1;
s[2]=&rele1;
s[3]=&td1;
s[4]=&tre1;
s[0]->printName();
cout<<"面积:"<<s[0]->printArea()<<endl;
s[1]->printName();
cout<<"面积:"<<s[1]->printArea()<<endl;
s[2]->printName();
cout<<"面积:"<<s[2]->printArea()<<endl;
s[3]->printName();
cout<<"面积:"<<s[3]->printArea()<<endl;
s[4]->printName();
cout<<"面积:"<<s[4]->printArea()<<endl;

cout<<"总面积:"<<s[0]->printArea()+s[1]->printArea()+s[2]->printArea()+s[3]->printArea()+s[4]->printArea()<<endl;
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120