7-2 抽象基类Shape派生3个类 (15分)

声明抽象基类Shape,由它派生出三个类,圆形Circle,矩形Rectangle,三角形Triangle,用一个函数输出三个面积。

输入格式:
在一行中依次输入5个数,圆的半径,长方形的高和宽,三角形的高和底,中间用空格分隔

输出格式:
圆的面积,长方形的面积,三角形的面积,小数点后保留2位有效数字,每个面积占一行。

输入样例:
在这里给出一组输入。例如:

3 3 4 3 4

输出样例:
在这里给出相应的输出。例如:

28.27
12.00
6.00

#include<iostream>
#include<iomanip>
using namespace std;
class Shape {
public:
    virtual void display() = 0;//纯虚函数,派生类重定义输出面积
};
//圆类
class Circle :public Shape {
    double radium;
public:
    Circle(double r) :radium(r) {}
    virtual void display();
};
//矩形类 
class Rectangle :public Shape {
    double lenth, width;
public:
    Rectangle(double l, double w) :lenth(l), width(w) {}
    virtual void display();
};
//三角形类 
class Triangle :public Shape {
    double high, bottom;
public:
    Triangle(double h, double b) :high(h), bottom(b) {}
    virtual void display();
};
//补写显示函数定义 
void Circle::display() {
    cout << fixed << setprecision(2) << 3.1415 * radium * radium << endl;;
}
void Rectangle::display() {
    cout << fixed << setprecision(2) << lenth * width << endl;
}
void Triangle::display() {
    cout << fixed << setprecision(2) << 0.5 * high * bottom << endl;
}
int main()
{
    double radium, high, lenth, width, bottom;
    cin >> radium >> lenth >> width >> high >> bottom;
    Shape* p[3];
    p[0] = new Circle(radium);
    p[1] = new Rectangle(lenth, width);
    p[2] = new Triangle(high, bottom);
    for (int i = 0; i < 3; i++) {
        p[i]->display();
        delete p[i];
    }
}

2020/4/27
By Suki
There are a lot of things they are waiting for me to do.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值