C++纯虚函数应用实例

#include <iostream>
using namespace std;
class Shape
{
public:
    Shape(){}
    ~Shape(){}
    virtual float getArea() = 0;
    virtual float getPerim() = 0;
};
class Rectangle:public Shape
{
public:
    Rectangle(float a,float b):length(a),width(b){}
    ~Rectangle(){}
    float getArea() {return length*width;}
    float getPerim(){return (length+width)*2;}
private:
    float length;
    float width;
};
class Circle:public Shape
{
public:
    Circle(float itsradius):radius(itsradius){}
    ~Circle(){}
    float getArea(){return 3.14*radius*radius;}
    float getPerim(){return 2*3.14*radius;}
private:
    float radius;
};
int main()
{
    Shape *sp;
    sp = new Rectangle(1,2);
    //Rectangle a(1.0,2.0);
    //Circle b(1);
    cout << sp->getArea()<<endl;
    delete sp;
    sp = new Circle(1);
    cout << sp->getArea() <<endl;
    delete sp;
    return 0;
}

posted @ 2021-03-13 12:22  Weisswire  阅读(96)  评论(0编辑  收藏  举报