1. 程式人生 > >寫一個程式,定義抽象基類Shape,由它派生出3個派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形)

寫一個程式,定義抽象基類Shape,由它派生出3個派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形)

 寫一個程式,定義抽象基類Shape,由它派生出3個派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形),用一個函式printArea分別輸出以上三者的面積,3個圖形的資料在定義物件時給定。

#include<iostream>
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<<s.printArea()<<endl;	
}
int main()
{
	Circle circle(12.6);
	cout<<"area of circle=";
	printArea(circle);
	Rectangle rectangle(4.5,8.4);
	cout<<"area of rectangle=";
	printArea(rectangle);
	Triangle triangle(4.5,8.4);
	cout<<"area of triangle=";
	printArea(triangle);
}
用基類指標陣列,使它每個元素指向一個派生類物件,求面積之和。

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;

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
請按任意鍵繼續. . .