39. 定义一个抽象类 Shape 用以计算面积,从中派生出计算长方形、梯形、圆形 面积的派生类。程序中通过基类指针来调用派生类中的虚函数,计算不同形状的面积。

39. 定义一个抽象类 Shape 用以计算面积,从中派生出计算长方形、梯形、圆形 面积的派生类。程序中通过基类指针来调用派生类中的虚函数,计算不同形状的 面积。

#include<iostream>

#define pi 3.14

using namespace std;

class Shape
{
public:
    virtual float getArea() const = 0;
};

class rectangle: public Shape       //长方形
{
private:
    float length;
    float width;
public:
    rectangle(float L,float W);
    float getArea() const override;
};

rectangle::rectangle(float L,float W):length(L),width(W){}
float rectangle::getArea() const{
    return length*width;
}

class Triangle: public Shape     //三角形
{
private:
    float Side;
    float Height; 
public:
    Triangle(float S,float H);
    float getArea() const override;
};

Triangle::Triangle(float S,float H){}
float Triangle::getArea() const{
    return Side*Height/2;
}

class Circle: public Shape            //圆形
{
private:
    float radius;
public:
    Circle(float R);
    float getArea() const override;
};

Circle::Circle(float R):radius(R){}
float Circle::getArea() const{
    return radius*radius*pi;
}

class Trapezoid: public Shape           //梯形
{
private:
    float upSide;
    float downSide;
    float height;
public:
    Trapezoid(float U,float D,float H);
    float getArea() const override;
};


Trapezoid::Trapezoid(float U,float D,float H):upSide(U),downSide(D),height(H){}
float Trapezoid::getArea() const{
    return (upSide+downSide)*height/2;
};

int main(){
    Shape* p[4];
    p[0] = new rectangle(4,5);
    p[1] = new Triangle(3,6);
    p[2] = new Circle(5);
    p[3] = new Trapezoid(3,7,6);

    for (int i = 0; i < 4; i++)
    {
        cout<<p[i]->getArea()<<endl;
    }
    return 0;
}
  • 16
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值