C++面向对象类的实例题目十一

题目描述:

写一个程序计算三角形,正方形和圆形3种图形的面积

程序代码:

#include<iostream>
#include<cmath>
#define PAI 3.1415
using namespace std;
class Shape
{
	public:
		virtual float area()	//定义一个求面积的成员函数 
		{
			return 0;
		}
		virtual void ShapeName() = 0;//定义一个纯虚函数 
};
class Triangle:public Shape
{
	public:
		Triangle(float x,float y,float z):a(x),b(y),c(z){};
		void ShapeName()
		{
			cout<<"Triangle:"<<endl; 
		}
		float area()
		{
			float p = (a+b+c)/2;
			float s = sqrt(p*(p-a)*(p-b)*(p-c));
			return s;
		}
	private:
		float a,b,c;
}; 
class Square:public Shape
{
	public:
		Square(float l):length(l){};
		void ShapeName()
		{
			cout<<"Square:"<<endl; 
		} 
		float area()
		{
			float s = length * length;
			return s;
		}
	private:
		float length;
};
class Circle:public Shape
{
	public:
		Circle(float r):radius(r){};
		void ShapeName()
		{
			cout<<"Square:"<<endl; 
		} 
		float area()
		{
			float s = PAI*radius*radius; 
			return s;
		}
	private:
		float radius;	
}; 
int main()
{
	Shape *pt;
	pt = new Triangle(3,4,5);
	pt->ShapeName();
	cout<<"Area:"<<pt->area()<<endl;
	cout<<"================================"<<endl; 
	pt = new Square(2.5);
	pt->ShapeName();
	cout<<"Area:"<<pt->area()<<endl;
	cout<<"================================"<<endl; 
	pt = new Circle(2.5);
	pt->ShapeName();
	cout<<"Area:"<<pt->area()<<endl;
	return 0;
}


结果输出:

Triangle:
Area:6
================================
Square:
Area:6.25
================================
Square:
Area:19.6344


posted @ 2014-01-02 16:53  千手宇智波  阅读(375)  评论(0编辑  收藏  举报