C++之纯虚函数和抽象类

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 //纯虚函数和抽象类
  6 //基类 是一个抽象类-抽象数据类型 类中至少有一个或者多个纯虚函数
  7 //不能够创建类的对象只能够继承 并且必须覆盖类的纯虚函数
  8 class Shape
  9 {
 10 public:
 11     Shape(){}
 12     virtual ~Shape(){}
 13     virtual double GetArea()=0;
 14     virtual double GetPerim()=0;
 15     virtual void Draw()=0; //纯虚函数 函数的定义可以写也可以不写
 16 };
 17 
 18 class Circle : public Shape
 19 {
 20 public:
 21     Circle(int itsRadius):itsRadius(itsRadius){}
 22     //只要是类中任何一个成员函数为虚函数则需要把析构函数也要做成虚函数
 23     virtual ~Circle(){}
 24     double GetArea(){return 3.14*itsRadius*itsRadius;}
 25     double GetPerim(){return 2*3.14*itsRadius;}
 26     void Draw();
 27 private:
 28     int itsRadius;
 29 };
 30 void Circle::Draw()
 31 {
 32     cout<<"画圆"<<endl;
 33 }
 34 
 35 class Rectangle : public Shape
 36 {
 37 public:
 38     Rectangle(int width,int height):width(width),height(height){}
 39     //只要是类中任何一个成员函数为虚函数则需要把析构函数也要做成虚函数
 40     virtual ~Rectangle(){}
 41     double GetArea(){return width*height;}
 42     double GetPerim(){return (width+height)+2;}
 43     void Draw();
 44     virtual int getWidth(){return width;}
 45     virtual int getHeight(){return height;}
 46 private:
 47     int width;
 48     int height;
 49 };
 50 void Rectangle::Draw()
 51 {
 52     for(int i=0;i<height;i++)
 53     {
 54         for(int j=0;j<width;j++)
 55         {
 56             cout<<"x";
 57         }
 58         cout<<"\n";
 59     }
 60 
 61 }
 62 
 63 class Square : public Rectangle
 64 {
 65 public:
 66     Square(int len);
 67     Square(int len,int width);
 68     virtual ~Square(){}
 69     double GetPerim(){return 4*getHeight();}
 70 };
 71 
 72 Square::Square(int len):Rectangle(len,len){}
 73 Square::Square(int len,int width):Rectangle(len,width)
 74 {
 75     if(getHeight()!=getWidth())
 76     {
 77         cout<<"这不是正方形"<<endl;
 78     }
 79 }
 80 int main()
 81 {
 82 //    Circle c(8);
 83 //    c.Draw();
 84 //    Rectangle r(10,5);
 85 //    r.Draw();
 86 //    Square s(8);
 87 //    s.Draw();
 88     int choice;
 89     bool fQuit=false;
 90     Shape *sp;
 91 
 92     while(fQuit==false)
 93     {
 94         cout<<"1、正方形==2、圆形==3、长方形==4、退出"<<endl;
 95         cin>>choice;
 96         switch(choice)
 97         {
 98         case 1:
 99             //指针必须new
100             sp=new Square(5);
101             break;
102         case 2:
103             sp=new Circle(3);
104             break;
105         case 3:
106             sp=new Rectangle(8,5);
107             break;
108         case 4:
109             fQuit=true;
110             break;
111         }
112         if(fQuit==false)
113         {
114             sp->Draw();
115             delete sp;
116         }
117     }
118     return 0;
119 }

 

posted @ 2020-04-12 15:27  萌萌~  阅读(170)  评论(0编辑  收藏  举报