定义一个抽象类shape,并由他派生出3个类,square(正方形),trapezoid(梯形)和triangle(三角形)。用虚函数分别计算几种图形的面积,并求他们的和。要求用基类指针数组,使它每一个元素指向一个派生类对象。
#include<iostream>
using namespace std;
class shape
{
protected:
double a, b,h;
public:
//求面积
virtual double area() = 0;
};
class square:public shape//正方形
{
public:
square(double a)
{
this->a = a;
}
virtual double area()
{
return a * a;
}
};
class trapezoid :public shape//梯形
{
public:
trapezoid(double a, double b, double h)
{
this->a = a;
this->b = b;
this->h = h;
}
virtual double area()
{
return (a + b)*h / 2;
}
};
class triangle :public shape//三角形
{
public:
triangle(double a, double h)
{
this->a = a;
this->h = h;
}
virtual double area()
{
return a * h / 2;
}
};
int main()
{
shape* p[2];
p[0] = new square(2.65);
p[1] = new trapezoid(5.6, 6.3, 30);
p[2] = new triangle(10, 20);
double sum = 0;
sum = p[0]->area() + p[1]->area() + p[2]->area();
printf("%lf", sum);//285.522500
cout << sum << endl;//285.522
system("pause");
return 0;
}