#include using namespace std;

const double PI = 3.14159265358979323846;

class Shape { protected: double area; double volume; public: virtual void calcArea() = 0; virtual void calcVolume() = 0; };

class Box : public Shape { private: double length; double width; double height; public: Box(double l, double w, double h) : length(l), width(w), height(h) {} void calcArea() { area = 2 * (length * width + width * height + height * length); } void calcVolume() { volume = length * width * height; } };

class Sphere : public Shape { private: double radius; public: Sphere(double r) : radius(r) {} void calcArea() { area = 4 * PI * radius * radius; } void calcVolume() { volume = 4.0 / 3.0 * PI * radius * radius * radius; } };

void calcShape(Shape* s) { s->calcArea(); s->calcVolume(); cout << "Area: " << s->area << endl; cout << "Volume: " << s->volume << endl; }

int main() { Box box(1, 2, 3); Sphere sphere(4); calcShape(&box); calcShape(&sphere); return 0; }


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

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