第八章 多态性习题8-6

  • Post author:
  • Post category:其他


题目:

请编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle,二者都有计算对象面积的函数getArea()、计算周长的函数getPerim()。

代码如下:

#include<iostream>
#define PI 3.14
using namespace std;
class Shape
{
public:
    Shape(){cout<<"shape构造"<<endl;}
    virtual double getArea()=0;
    virtual double getPerim()=0;
    ~Shape(){cout<<"shape析构"<<endl;}
};
class Rectangle:public Shape
{
public:
    Rectangle(double h,double w):height(h),weight(w){cout<<"rectangle 构造"<<endl;}
    double getArea(){return height*weight;}
    double getPerim(){return 2*(height+weight);}
    ~Rectangle(){cout<<"rectangle 析构"<<endl;}
private:
    double height;
    double weight;
};
class Circle:public Shape
{
public:
    Circle(double r):radius(r){cout<<"Circle 构造"<<endl;}
    double getArea(){return PI*radius*radius;}
    double getPerim(){return 2*PI*radius;}
    ~Circle(){cout<<"Circle 析构"<<endl;}
private:
    double radius;
};
int main()
{
    Rectangle r(3.5,2.0);
    cout<<"矩形面积为:"<<r.getArea();
    cout<<"   矩形周长为:"<<r.getPerim()<<endl;
    Circle c(3.0);
    cout<<"圆的面积为:"<<c.getArea();
    cout<<"   圆的周长为:"<<c.getPerim()<<endl;
    return 0;
}

运行结果:

同时可以观察构造函数及析构函数的调用顺序



版权声明:本文为duluchen原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。