利用C++求不規則圖形面積
#include <iostream>
using namespace std;
class Shape
{public:
virtual float area() const =0;
};
class Circle:public Shape
{public:
Circle(float r):radius(r){}
virtual float area() const {return 3.14159*radius*radius;};
protected:
float radius;
};
class Square:public Shape
{
public:
Square(float s):side(s){}
virtual float area() const {return side*side;}
protected:
float side;
};
class Rectangle:public Shape
{public:
Rectangle(float w,float h):width(w),height(h){}
virtual float area() const {return width*height;}
protected:
float width,height;
};
class Trapezoid:public Shape
{public:
Trapezoid(float t,float b,float h):top(t),bottom(t),height(h){}
virtual float area() const {return 0.5*(top+bottom)*height;}
protected:
float top,bottom,height;
};
class Triangle:public Shape
{public:
Triangle(float w,float h):width(w),height(h){}
virtual float area()const {return 0.5*width*height;}
protected:
float width,height;
};
int main()
{
Circle circle(7);
Square square(2.5);
Rectangle rectangle(4,8);
Trapezoid trapezoid(2,6,3.2);
Triangle triangle(4,8.4);
Shape *p[5]={&circle,&square,&rectangle,&trapezoid,&triangle};
float areas=0;
for(int i=0;i<5;i++)
{areas=areas+p[i]->area();}
cout<<"all areas="<<areas<<endl;
return 0;
}