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

题目描述:

写一个程序计算正方体、球体和圆柱体的表面积和体积

程序代码:

 

#include<iostream>

#define PAI 3.1415

using namespace std;

class Shape

{

	public:

		virtual void ShapeName()=0;

		virtual void area()

		{

			return ;

		}

		virtual void volume()

		{

			return ;

		}

};

class Cube:public Shape

{

	public:

		Cube(float len):length(len){};

		void ShapeName()

		{

			cout<<"Cube:"<<endl;

		}

		void area()

		{

			double s = 6*length*length;

			cout<<"Area:"<<s<<endl;

		}

		void volume()

		{

			double v = length*length*length;

			cout<<"Volume:"<<v<<endl;

		}

	private:

		float length;

};

class Sphere:public Shape

{

	public:

		Sphere(float r):radius(r){};

		void ShapeName()

		{

			cout<<"Sphere:"<<endl;

		}

		void area()

		{

			double s = 4*radius*radius*PAI;

			cout<<"Area:"<<s<<endl;

		}

		void volume()

		{

			double v = (4*radius*radius*radius*PAI)/3;

			cout<<"Volume:"<<v<<endl;

		}

	private:

		float radius;

};

class Cylinder:public Shape

{

	public:

		Cylinder(float r,float h):radius(r),length(h){};

		void ShapeName()

		{

			cout<<"Cylinder:"<<endl;

		}

		void area()

		{

			double s = radius*radius*PAI + 2*PAI*radius*length;

			cout<<"Area:"<<s<<endl;

		}

		void volume()

		{

			double v = radius*radius*PAI*length;

			cout<<"Volume:"<<v<<endl;

		}

	private:

		float radius;

		float length;

};

int main()

{

	Shape * pt;

	pt = new Cube(2);

	pt->ShapeName();

	pt->area();

	pt->volume();

	cout<<"==========================="<<endl;

	pt = new Sphere(2);

	pt->ShapeName();

	pt->area();

	pt->volume();

	cout<<"==========================="<<endl;

	pt = new Cylinder(2,2);

	pt->ShapeName();

	pt->area();

	pt->volume();

	cout<<"==========================="<<endl; 

} 


 

 

结果输出:

 

Cube:

Area:24

Volume:8

===========================

Sphere:

Area:50.264

Volume:33.5093

===========================

Cylinder:

Area:37.698

Volume:25.132

===========================


 


 

你可能感兴趣的:(面向对象)