c++实验九(一)多态性和抽象类

c++实验九(一)多态性和抽象类,第1张

【实验目的】

  1. 对类多重继承和多态的含义进行理解;
  2. 掌握类的多重继承方法及多态性;

【实验内容】

  1. 类的层次结构的顶层是抽象基类Shape(形状)。Point(点), Circle(圆), Rectangle(矩形)都是Shape类的直接派生类和间接派生类。

class Shape

{public:

 virtual float area( ) const {return 0.0;}//虚函数

 virtual void shapeName() const =0; //纯虚函数

};

实现Point(点), Circle(圆), Rectangle(矩形),并通过主函数分别定义其对象,用Shape类型的指针分别指向这些对象,并用指针调用area()和shapeName()函数,体会动态多态性的含义。

  1. Shape.h

class Shape

{

    public:

        Shape():x(0),y(0){}

        Shape(int a,int b):x(a),y(b){}

        virtual float area( ) const {return 0.0;}

    virtual void shapeName() const =0;

    protected:

        int x;

        int y;

};

Point.h

class Point:public Shape

{

    public:

        Point(){}

        Point(int x,int y):Shape(x,y){}

        float area() const;

        void shapeName() const;

    protected:

        int x;

        int y;

};

Point.cpp

float Point::area() const

{

    cout<<"点的坐标为:("<

}

void Point::shapeName() const

{

    cout<<"点"<

}

Circle.h

class Circle:public Point

{

    public:

        Circle():r(0){}

        Circle(int x,int y,double r1):Point(x,y),r(r1)

        {

        }

        float area() const;

        void shapeName() const;

    protected:

        double r;

};

Circle.cpp

float Circle::area() const

{

    float area;

    area=3.14*r*r;

    return area;

}

void Circle::shapeName() const

{

    cout<<"圆"<

}

Rectangle.h

class Rectangle:public Shape

{

    public:

        Rectangle():length(0),width(0){}

        Rectangle(int x,int y,int l,int w):Shape(x,y),length(l),width(w){}

        float area() const;

        void shapeName() const;

    protected:

        int length;

        int width;

};

Rectangle.cpp

float Rectangle::area() const

{

    float area;

    area=length*width;

    return area;

}

void Rectangle::shapeName() const

{

    cout<<"矩形"<

}

main.cpp

int main()

{

    //Shape s(1,2);

    Point p(2,3);

    Circle c(2,4,3);

    Rectangle r(2,2,3,4);

    Shape *st;

    st=&c;

    cout<<"圆的面积:"<area()<

    st=&r;

    cout<<"矩形面积:"<area()<

    return 0;

}

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1324471.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存