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

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

#include <iostream>
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.
}

运行结果:
在这里插入图片描述

  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值