请使用面向对象编程思想用cpp简单编写代码实现如下功能验证继承的多根性和抽象类等技能点。 Shape形状类有面积和体积两个属性和计算面积、计算体积两个虚方法;Box长方形类是形状类中的一种特有长、宽和高属性;Sphere球类特有半径属性。编写独立的函数实现计算任何形状类对象的面积和体积的功能。M_PI未定义
#include
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 著作权归作者所有。请勿转载和采集!