贵州大学oj C++ 第五次 1.抽象的三维立体形状类Shape3D

记录学习日常 代码可能有错 大家多多包涵 有好的建议提出的话 我会开心接纳 初学阶段 

定义一个抽象的三维立体形状类Shape3D,该类有一个数据成员shapeName(形状名称),一个纯虚函数calVolume(计算体积),用于计算三维立体形状的体积。

(1)请完成Shape3D类的定义,定义你认为必要的任何成员;

(2)请为Shape3D类定义公有派生类Cube(正方体类)、Cuboid(长方体类),Sphere(球体类)和Cone(圆锥体类)。Cube类有side(边长)数据成员;Cuboid类有length、width和height数据成员(分别代表长、宽、高);Sphere类有radius(半径)数据成员;Cone类有radius和height数据成员(分别代表底面半径和高)。在这些派生类中分别实现纯虚函数calVolume。

(3)在主函数中定义Shape3D的指针并分别指向不同的派生类对象,调用calVolume计算不同三维立体形状的体积。

main函数已经完成,请根据main函数的内容完成以上所有类的定义。在程序中,请使用下面的圆周率定义并使用该圆周率进行计算:

const double PI=3.14159265;

int main(){

double length,width,height,radius;

Shape3D *sp;

cin>>length;

Cube cube("Cube",length);

cin>>length>>width>>height;

Cuboid cuboid("Cuboid",length,width,height);

cin>>radius;

Sphere sphere("Sphere",radius);

cin>>radius>>height;

Cone cone("Cone",radius,height);

为了满足用户的需求,以下是一个贵州大学 OJ 平台上面向对象编程第八次作业内容相关的题目及答案。该题目涉及使用虚函数和抽象的概念。 ### 题目描述 编写一个抽象 `Shape`,在此基础上派生出两个子 `Rectangle`(长方形)和 `Circle`(圆)。这两个需要实现计算面积的函数 `getArea()` 和计算周长的函数 `getPerim()`。 为了避免精度问题,取圆周率 π=3。 --- ### 代码实现 ```cpp #include <bits/stdc++.h> using namespace std; // 抽象 Shape class Shape { public: virtual int getArea() = 0; // 纯虚函数,获取面积 virtual int getPerim() = 0; // 纯虚函数,获取周长 }; // Rectangle 继承自 Shape class Rectangle : public Shape { private: int length, width; public: Rectangle(int l, int w) : length(l), width(w) {} int getArea() override { return length * width; } int getPerim() override { return 2 * (length + width); } }; // Circle 继承自 Shape class Circle : public Shape { private: int radius; public: Circle(int r) : radius(r) {} int getArea() override { return 3 * radius * radius; // π = 3 } int getPerim() override { return 2 * 3 * radius; // π = 3 } }; // 主函数 int main() { int x, y, r; cin >> x >> y >> r; Shape* shape = new Rectangle(x, y); cout << shape->getArea() << '-' << shape->getPerim() << " "; shape = new Circle(r); cout << shape->getArea() << '-' << shape->getPerim() << " "; delete shape; // 释放内存 return 0; } ``` --- ### 示例输入输出 **输入:** ``` 5 3 4 ``` **输出:** ``` 15-16 48-24 ``` **解释:** - 长方形的长为 5,宽为 3: - 面积 = 5 × 3 = 15 - 周长 = 2 × (5 + 3) = 16 - 圆的半径为 4: - 面积 = 3 × 4² = 48 - 周长 = 2 × 3 × 4 = 24 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值