打卡 抽象基类Shape派生3个类 C++多态

发布时间 2023-04-25 22:05:58作者: 起名字真难_qmz

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

输入格式:

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

输出格式:

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

输入样例:

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

3 3 4 3 4
 

输出样例:

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

28.27
12.00
6.00

思路:简单的基类派生和虚函数重载

代码实现

#include <iostream>
#include <cmath>
const double PI = 3.1415926;
class Shape {
public:
virtual double area() const = 0;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const {
return PI * radius * radius;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const {
return width * height;
}
};
class Triangle : public Shape {
private:
double base, height;
public:
Triangle(double b, double h) : base(b), height(h) {}
double area() const {
return 0.5 * base * height;
}
};
int main() {
double radius, width, height, base, tri_height;
std::cin >> radius >> width >> height >> base >> tri_height;

Circle c(radius);
Rectangle r(width, height);
Triangle t(base, tri_height);

std::cout << std::fixed;
std::cout.precision(2);
std::cout << c.area() << std::endl;
std::cout << r.area() << std::endl;
std::cout << t.area() << std::endl;
return 0;
}