多态性2(图形的面积)
定义一个形状类shape,将它作为基类派生出类:circle(圆)、triangle(三角形)和rectangle(长方形)。
分别定义这些派生类并且定一个虚函数来计算各个形状的面积。
#include
#include<math.h>
#include
using namespace std;
///基类Shape
class Shape
{
public:
void virtual printArea() = 0;//纯虚函数
};
//派生类Circle
class Circle : public Shape
{
public:
Circle(double r = 0):radius®{}//构造函数
void printArea(){cout<<fixed<<setprecision(3)<<3.14 * radius * radius<<endl;}
private:
double radius;//数据成员,表示半径
};
//派生类Rectangle
class Rectangle : public Shape
{
public:
Rectangle(double w,double h):width(w),height(h){}//构造函数
void printArea(){cout<<fixed<<setprecision(3)<<width * height<<endl;}
private:
double width;//数据成员,表示宽
double height;//数据成员,表示长
};
//派生类Triangle
class Triangle : public Shape
{
public:
Triangle(double w,double h,double u):width(w),height(h),gun(u){} //构造函数
void printArea(){
double f;
f=(width+height+gun)/2;
cout<<fixed<<setprecision(3)<<sqrt(f*(f-width)(f-height)(f-gun))<<endl;}
private:
double width;//数据成员,表示底
double height;//数据成员,表示高
double gun;
};
//主函数
int main()
{
Shape *s;
double a,b,c,d,e,f;
while(cin>>a>>b>>c>>d>>e>>f){
Circle circle(a);
Rectangle rectangle(e,f);
Triangle triangle(b,c,d);
s = &circle;
s->printArea();
s = ▵
s->printArea();
s = &rectangle;
s->printArea();
}
return 0;
}