C++面向对象类的实例题目十二
2024-10-19 07:29:17
题目描述:
写一个程序计算正方体、球体和圆柱体的表面积和体积
程序代码:
#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
===========================
最新文章
- AD账号创建日期、最近一次登录时间、最近一次重置密码时间查询
- C++/Python 混合编程 Clion IDE 搭建
- TextMate 小小心得
- [HIHO1062] 最近公共祖先&#183;一(lca, 并查集, 二分, 神trick)
- Textview下划线注册用户跳转实现
- Deep Learning Workbench Installation Notes
- scjp考试准备 - 4 - 关于数组
- Linq的简单查询
- python之math模块
- python手记(47)
- CAP 介绍及使用【视频】
- mapreduce解析执行sql流程
- Docker的介绍及安装
- 微信网页悬浮窗交互效果的web实现
- Xamarin.Android 获取手机IP地址
- PCB封装步骤教程
- LEO原创-FMX之你不知道的ARC
- kali安装搜狗输入法
- js之 data-*自定义属性
- 最长连续子序列 Longest Consecutive Sequence
热门文章
- Google Guava 库用法整理<;转>;
- Swift开发教程--设置UIViewController的背景透明
- jquery easy ui 简单字段选择搜索实现
- R工具包
- Openfire配置过程,以及与php交互注意事项。
- 关于Struts2有时候出现的莫名其妙的错误
- dlib VS2013 face关键点检测与对齐
- Intellij Idea14 jstl标签的引入
- php数组函数常见的那些
- Java Error: java.lang.UnsupportedClassVersionError: ...bad major version at offset=6