写一个程序,定义抽象基类Shape,由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)、Triangle(三角形)

 写一个程序,定义抽象基类Shape,由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。

#include
using namespace std;
class Shape
{
	public:
	virtual float printArea() const {return 0.0;};	
};
class Circle:public Shape
{
	public:
	 Circle(float =0);
	 virtual float printArea() const {return 3.14159*radius*radius;}	
	protected:
		float radius;
};
Circle::Circle(float r):radius(r)
{
}
class Rectangle:public Shape
{
	public:
		Rectangle(float =0,float =0);
	virtual float printArea() const;
	protected:
		float height;
		float width;
};
Rectangle::Rectangle(float w,float h):width(w),height(h){
}
float Rectangle::printArea()const
{
	return width*height;
}
class Triangle:public Shape
{
	public:
		Triangle(float =0,float =0);
	virtual float printArea() const;
	protected:
		float height;
		float width;
};
Triangle::Triangle(float w,float h):width(w),height(h){
}
float Triangle::printArea()const
{
	return 0.5*width*height;
}
void printArea(const Shape&s)
{
cout<Shape *p[3]={&circle,&rectangle,&triangle};
	double area=0.0;
	for(int i=0;i<3;i++) 
	{
		area+=p[i]->printArea();
	}
	cout<<"total of all area= "<

area of circle=498.759
area of rectangle=37.8
area of triangle=18.9
total of all area= 555.459
--------------------------------
Process exited after 0.4691 seconds with return value 0
请按任意键继续. . .

你可能感兴趣的:(c++学习)