以下是 C++ 代码实现:

#include <iostream>
#include <cmath>
using namespace std;

class Shape {
private:
    double x;
    double y;

public:
    Shape(double a, double b): x(a), y(b) {}
    virtual void show_area() = 0;
    void set_mem(double a, double b) {
        x = a;
        y = b;
    }
};

class Triangle : public Shape {
public:
    Triangle(double a, double b): Shape(a, b) {}
    void show_area() {
        cout << 'Triangle area: ' << 0.5 * get_x() * get_y() << endl;
    }
private:
    double get_x() { return Shape::x; }
    double get_y() { return Shape::y; }
};

class Square : public Shape {
public:
    Square(double a, double b): Shape(a, b) {}
    void show_area() {
        cout << 'Square area: ' << get_x() * get_y() << endl;
    }
private:
    double get_x() { return Shape::x; }
    double get_y() { return Shape::y; }
};

class Circle : public Shape {
public:
    Circle(double a, double b): Shape(a, b) {}
    void show_area() {
        cout << 'Circle area: ' << M_PI * pow(get_x(), 2) << endl;
    }
private:
    double get_x() { return Shape::x; }
    double get_y() { return Shape::y; }
};

int main() {
    Shape* p;
    Triangle t(3, 4);
    Square s(5, 5);
    Circle c(2, 0);

    p = &t;
    p->show_area();

    p = &s;
    p->show_area();

    p = &c;
    p->show_area();

    return 0;
}

输出结果:

Triangle area: 6
Square area: 25
Circle area: 12.5664
C++ Shape 类实现:三角形、正方形和圆形的面积计算

原文地址: https://www.cveoy.top/t/topic/jN0E 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录