zoukankan      html  css  js  c++  java
  • 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
    ===========================



  • 相关阅读:
    Linux文件结构
    磁盘分区
    BASH简介
    磁盘的基本概念
    Linux文件操作
    创建文件系统
    文件系统挂载
    一些常用命令
    asp.net创建PPT
    asp.net创建、删除、移动文件夹 文件
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3503352.html
Copyright © 2011-2022 走看看