xt12-4.cpp
上传用户:liubin
上传日期:2022-06-13
资源大小:85k
文件大小:2k
源码类别:

书籍源码

开发平台:

Visual C++

  1. #include <iostream>
  2. using namespace std;
  3. //定义抽象基类Shape
  4. class Shape
  5. {public:
  6.  virtual double area() const =0;            //纯虚函数
  7. };
  8. //定义Circle类
  9. class Circle:public Shape
  10. {public:
  11. Circle(double r):radius(r){}                                     //结构函数
  12.   virtual double area() const {return 3.14159*radius*radius;};   //定义虚函数
  13.  protected:
  14.   double radius;                                                 //半径
  15. };
  16. //定义Rectangle类
  17. class Rectangle:public Shape
  18. {public:
  19.  Rectangle(double w,double h):width(w),height(h){}               //结构函数
  20.  virtual double area() const {return width*height;}              //定义虚函数
  21.  protected:
  22.   double width,height;                                           //宽与高
  23. };
  24. class Triangle:public Shape
  25. {public:
  26.   Triangle(double w,double h):width(w),height(h){}                //结构函数
  27.   virtual double area() const {return 0.5*width*height;}          //定义虚函数
  28.  protected:
  29.   double width,height;                                            //宽与高
  30. };
  31. //输出面积的函数
  32. void printArea(const Shape &s)
  33. {cout<<s.area()<<endl;}                                            //输出s的面积
  34. int main()
  35. {
  36.  Circle circle(12.6);                                             //建立Circle类对象circle
  37.  cout<<"area of circle    =";          
  38.  printArea(circle);                                               //输出circle的面积
  39.  Rectangle rectangle(4.5,8.4);                                    //建立Rectangle类对象rectangle
  40.  cout<<"area of rectangle =";                                     
  41.  printArea(rectangle);                                            //输出rectangle的面积
  42.  Triangle triangle(4.5,8.4);                                      //建立Triangle类对象 
  43.  cout<<"area of triangle  =";
  44.  printArea(triangle);           //输出triangle的面积
  45.  return 0;
  46. }