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

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

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

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

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

3 3 4 3 4

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

28.27
12.00
6.00

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

你可能感兴趣的:(PTA习题)