计算三角形的周长和面积的类
class shape
{
public:
virtual float perimeter() const{ return 0; }
virtual float area()const { return 0; }
virtual const char* name()const
{
return "抽象图形";
}
};
class point
{
float x;
float y;
public:
point(float x0, float y0) :x(x0), y(y0){}
float getX()const { return x; }
float getY()const { return y; }
};
class triangle :public shape
{
point point1, point2, point3;
public:
triangle(point p1, point p2, point p3) :point1(p1), point2(p2), point3(p3){}
float perimeter()const;
float area()const;
const char* name()const{ return "三角形"; }
};
float length(point p1, point p2)
{
return sqrt((p1.getX() - p2.getX())*(p1.getX() - p2.getX()) + (p1.getY() - p2.getY())*(p1.getY() - p2.getY()));
}
float triangle::perimeter()const
{
float x = length(point1, point2);
float y = length(point1, point3);
float z = length(point3, point2);
return length( point1, point2) + length( point1, point3) + length( point2, point3);
}
float triangle::area()const
{
float s = perimeter() / 2.0;
return sqrt(s*(s - length(point1, point2))
*(s - length(point2, point3))
*(s - length(point3, point1)));
}
void show(shape& shape)
{
cout << "此图形是一个 " << shape.name() << ",周长= " << shape.perimeter() <<
", 面积=" << shape.area() << endl;
}
int _tmain()
{
shape s;
triangle tri(point(0, 2), point(2, 0), point(0, 0));
show(s);
show(tri);
return 0;
}