请使用面向对象编程思想用cpp简单编写代码实现如下功能验证继承的多根性和抽象类等技能点。 Shape形状类有面积和体积两个属性和计算面积、计算体积两个虚方法;Box长方形类是形状类中的一种特有长、宽和高属性;Sphere球类特有半径属性。编写独立的函数实现计算任何形状类对象的面积和体积的功能。
#include
using namespace std;
class Shape { protected: double area; double volume; public: virtual void calculateArea() = 0; virtual void calculateVolume() = 0; double getArea() { return area; } double getVolume() { return volume; } };
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 calculateArea() { area = 2 * (length * width + width * height + height * length); } void calculateVolume() { volume = length * width * height; } };
class Sphere : public Shape { private: double radius; public: Sphere(double r) { radius = r; } void calculateArea() { area = 4 * M_PI * pow(radius, 2); } void calculateVolume() { volume = 4.0 / 3.0 * M_PI * pow(radius, 3); } };
void calculate(Shape* s) { s->calculateArea(); s->calculateVolume(); }
int main() { Box b(2, 3, 4); Sphere s(5);
calculate(&b);
cout << "Box area: " << b.getArea() << endl;
cout << "Box volume: " << b.getVolume() << endl;
calculate(&s);
cout << "Sphere area: " << s.getArea() << endl;
cout << "Sphere volume: " << s.getVolume() << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/b4IZ 著作权归作者所有。请勿转载和采集!