立体类族共有的抽象类

  1. #ifndef CSOLID_H_INCLUDED  
  2. #define CSOLID_H_INCLUDED  
  3.   
  4. class CSolid  
  5. {  
  6. public:  
  7.     virtual double surfaceArea() = 0;  
  8.     virtual double volume() = 0;  
  9. };  
  10.   
  11. class CCube:public CSolid  
  12. {  
  13. public:  
  14.     CCube(double l, double w, double h):length(l),width(w),height(h){}  
  15.     double surfaceArea();  
  16.     double volume();  
  17. private:  
  18.     double length;  
  19.     double width;  
  20.     double height;  
  21. };  
  22.   
  23. class CBall:public CSolid  
  24. {  
  25. public:  
  26.     CBall(double r):radius(r){}  
  27.     double surfaceArea();  
  28.     double volume();  
  29. private:  
  30.     static constexpr double PI = 3.1415926;  
  31.     double radius;  
  32. };  
  33.   
  34. class CCylinder:public CSolid  
  35. {  
  36.     public:  
  37.     CCylinder(double r, double h):radius(r),height(h){}  
  38.     double surfaceArea();  
  39.     double volume();  
  40. private:  
  41.     static constexpr double PI = 3.1415926;  
  42.     double radius;  
  43.     double height;  
  44. };  
  45.   
  46. #endif // CSOLID_H_INCLUDED  
CSolid.cpp

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include "CSolid.h"  
  2.   
  3. double CCube::surfaceArea()  
  4. {  
  5.     return (length*width + length*height + width*height)*2;  
  6. }  
  7.   
  8. double CCube::volume()  
  9. {  
  10.     return length * height * width;  
  11. }  
  12.   
  13. double CBall::surfaceArea()  
  14. {  
  15.     return 4 * PI * radius * radius;  
  16. }  
  17.   
  18. double CBall::volume()  
  19. {  
  20.     return (4*PI*radius*radius*radius) / 3;  
  21. }  
  22.   
  23. double CCylinder::surfaceArea()  
  24. {  
  25.     return 2*PI*radius*height + PI*radius*radius*2;  
  26. }  
  27.   
  28. double CCylinder::volume()  
  29. {  
  30.     return PI*radius*radius*height;  
  31. }  

main.cpp

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. #include "CSolid.h"  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     CSolid *p = nullptr;  
  8.     CCube cube(1,2,3);  
  9.     p = &cube;  
  10.     cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;  
  11.     CBall ball(2);  
  12.     p = &ball;  
  13.     cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;  
  14.     CCylinder cylinder(2,2);  
  15.     p = &cylinder;  
  16.     cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;  
  17.     return 0;  
  18. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值