cpp课程设计实验题:编写程序,定义抽象基类Shape(形状),由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)和Square 正方形),用函数函数ShowArea()分别显

编写程序,定义抽象基类Shape(形状),由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)和Square 正方形),用函数函数ShowArea()分别显示各种图形的面积,最后还要显示所有图形的总面积。要求用基类指针数组,使它的每一个元素指向一一个派生类对象。
源代码如下:

#include 
using namespace std;
class Shape
{
public:
    virtual double area() const =0;
};

class Circle:public Shape
{
public:
    Circle(double r):radius(r){}
    virtual double area() const {return 3.14*radius*radius;};
    void ShowArea()
    {
        cout<<"圆形的面积为:"<<area()<<endl;
    }
protected:
    double radius;
};

class Rectangle:public Shape
{
public:
    Rectangle(double w,double h):width(w),height(h){}
    virtual double area() const {return width*height;}
    void ShowArea()
    {
        cout<<"矩形的面积为:"<<area()<<endl;
    }
protected:
    double width,height;
};

class Square:public Shape
{
public:
    Square(double w):width(w){}
    virtual double area() const {return width*width;}
    void ShowArea()
    {
        cout<<"正方形的面积为:"<<area()<<endl;
    }
protected:
    double width;
};

int main()
{
    Circle c1(5);
    c1.ShowArea();
    Rectangle r1(5,6);
    r1.ShowArea();
    Square t1(4);
    t1.ShowArea();
    Shape *pt[3]={&c1,&r1,&t1};
    double areas=0.0;
    for(int i=0;i<3;i++)
    {
        areas=areas+pt[i]->area();
    }
    cout<<"总面积为:"<<areas<<endl;
    return 0;
    //This code was written by gfh in SCMZU.
}

运行结果:
cpp课程设计实验题:编写程序,定义抽象基类Shape(形状),由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)和Square 正方形),用函数函数ShowArea()分别显_第1张图片

你可能感兴趣的:(c++)