#include <iostream>
using namespace std;

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

class Rectangle : public Shape{
public:
    Rectangle(float w, float h){
        width = w;
        height = h;
    }
    float getArea(){
        return width * height;
    }
    float getPerim(){
        return 2 * (width + height);
    }
private:
    float width;
    float height;
};

class Circle : public Shape{
public:
    Circle(float r){
        radius = r;
    }
    float getArea(){
        return 3.14 * radius * radius;
    }
    float getPerim(){
        return 2 * 3.14 * radius;
    }
private:
    float radius;
};

int main(){
    Rectangle r(5, 10);
    Circle c(3);
    cout << 'Rectangle Area: ' << r.getArea() << endl;
    cout << 'Rectangle Perimeter: ' << r.getPerim() << endl;
    cout << 'Circle Area: ' << c.getArea() << endl;
    cout << 'Circle Perimeter: ' << c.getPerim() << endl;
    return 0;
}
C++ 抽象类 Shape:定义图形类,计算面积和周长

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

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