#include using namespace std;

class Shape { public: virtual double GetArea() = 0; };

class Rectangle : public Shape { private: double m_Width; double m_Height; public: Rectangle(double width = 0, double height = 0) : m_Width(width), m_Height(height) {}

double GetArea() {
    return m_Width * m_Height;
}

};

class Circle : public Shape { private: double m_Radius; public: Circle(double radius = 0) : m_Radius(radius) {}

double GetArea() {
    return 3.14 * m_Radius * m_Radius;
}

};

int main() { Shape* shapes[2]; shapes[0] = new Rectangle(4, 5); shapes[1] = new Circle(3);

for (int i = 0; i < 2; i++) {
    cout << "Area: " << shapes[i]->GetArea() << endl;
}

delete shapes[0];
delete shapes[1];

return 0;

}

C++ 抽象类 Shape 派生 Rectangle 和 Circle 计算面积

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

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