编写程序,定义抽象类Shape,由它派生出5个派生类:Circle(圆形) Square(正方形) Rectangle(长方形) Trapezoid(梯形) Triangle(三角形)。用虚函数分别计算几个图形的面积。要求使用基类指针,使其指向派生类对象:
#include<iostream.h>
const double PI=3.14;
class Shape
{
public:
virtual double area()=0;
virtual void shapeName()=0;
};
class Circle:public Shape
{
private:
double r;
public:
Circle(double rr)
{
r=rr;
}
virtual double area()
{
return PI*r*r;
}
virtual void shapeName()
{
cout<<"This is a Circle.";
}
};
class Square:public Shape
{
private:
double x;
public:
Square(double xx)
{
x=xx;
}
virtual double area()
{
return x*x;
}
virtual void shapeName()
{
cout<<"This is a Square.";
}
};
class Rectangle:public Shape
{
private:
double x1,y1;
public:
Rectangle(double m,double n)
{
x1=m;
y1=n;
}
virtual double area()
{
return x1*y1;
}
virtual void shapeName()
{
cout<<"This is a Rectangle.";
}
};
class Trapezoid:public Shape
{
private:
double x2,y2,h;
public:
Trapezoid(double a,double b,double hh)
{
x2=a;
y2=b;
h=hh;
}
virtual double area()
{
return (x2+y2)*h/2;
}
virtual void shapeName()
{
cout<<"This is a Trapezoid.";
}
};
class Triangle:public Shape
{
private:
double x3,h1;
public:
Triangle(double e,double d)
{
x3=e;
h1=d;
}
virtual double area()
{
return x3*h1/2;
}
virtual void shapeName()
{
cout<<"This is a Triangle.";
}
};
void main()
{
Shape *p;
Circle c(2);
Square s(3);
Rectangle cf(6,6);
Trapezoid t(3,5,4);
Triangle sj(7,5);
p=&c;
p->shapeName();
cout<<"area="<<p->area()<<endl;
p=&s;
p->shapeName();
cout<<"area="<<p->area()<<endl;
p=&cf;
p->shapeName();
cout<<"area="<<p->area()<<endl;
p=&t;
p->shapeName();
cout<<"area="<<p->area()<<endl;
p=&sj;
p->shapeName();
cout<<"area="<<p->area()<<endl;
}