形状类族中的纯虚函数

来源:互联网 发布:sql查询数据库的大小 编辑:程序博客网 时间:2024/06/04 23:25
  1. #ifndef SHAPE_H_INCLUDED  
  2. #define SHAPE_H_INCLUDED  
  3.   
  4. class Shape  
  5. {  
  6. public:  
  7.     virtual double area() = 0;  
  8. };  
  9.   
  10. class Circle:public Shape  
  11. {  
  12. public:  
  13.     Circle(double r = 0):radius(r){}  
  14.     double area();  
  15. private:  
  16.     constexpr static double PI = 3.1415926;  
  17.     double radius;  
  18. };  
  19.   
  20. class Rectangle:public Shape  
  21. {  
  22. public:  
  23.     Rectangle(double h = 0,double w = 0):height(h),width(w){}  
  24.     double area();  
  25. private:  
  26.     double height;  
  27.     double width;  
  28. };  
  29.   
  30. class Triangle:public Shape  
  31. {  
  32. public:  
  33.     Triangle(double bM = 0, double h = 0):bottomMargin(bM),height(h){}  
  34.     double area();  
  35. private:  
  36.     double bottomMargin;  
  37.     double height;  
  38. };  
  39. #endif // SHAPE_H_INCLUDED  
Shape.cpp

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include "Shape.h"  
  2.   
  3. double Circle::area()  
  4. {  
  5.     return radius * radius * PI;  
  6. }  
  7.   
  8. double Rectangle::area()  
  9. {  
  10.     return height * width;  
  11. }  
  12.   
  13. double Triangle::area()  
  14. {  
  15.     return (height * bottomMargin)/2;  
  16. }  

main.cpp

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include "Shape.h"  
  3. using namespace std;  
  4.   
  5.   
  6. int main()  
  7. {  
  8.     Circle c1(12.6),c2(4.9);  
  9.     Rectangle r1(4.5,8.4),r2(5.0,2.5);  
  10.     Triangle t1(4.5,8.4),t2(3.4,2.8);  
  11.     Shape* pt[6] = {&c1,&c2,&r1,&r2,&t1,&t2};  
  12.     double areas = 0.0;  
  13.     for(int i = 0; i < 6; ++i)  
  14.         areas += pt[i]->area();  
  15.     cout << "total of all areas =" << areas << endl;  
  16.     return 0;  
  17. }  
0 0
原创粉丝点击