C++程序创建盒子并计算体积,并使用小于运算符进行检查

c++程序创建盒子并计算体积,并使用小于运算符进行检查

假设我们必须定义一个具有很少条件的盒子类。如下 –

三个属性 l、b 和 h 分别表示长度、宽度和高度(这些是私有变量)

定义一个非参数化构造函数来将 l、b、h 设置为 0,并定义一个参数化构造函数来初始设置值。

定义每个属性的getter方法

立即学习“C++免费学习笔记(深入)”;

定义一个函数calculateVolume()获取盒子的体积

重载小于运算符(

创建一个可以计算创建的框数量的变量。

因此,如果我们输入三个框 (0, 0, 0) (5, 8, 3), (6, 3, 8) 并显示每个框的数据,并检查第三个框是否较小是否大于第二个,并找到较小盒子的体积,并通过计数变量打印它们有多少个盒子。

然后输出将是

Box 1: (length = 0, breadth = 0, width = 0)Box 2: (length = 5, breadth = 8, width = 3)Box 3: (length = 6, breadth = 3, width = 8)Box 3 is smaller, its volume: 120There are total 3 box(es)

为了解决这个问题,我们将按照以下步骤操作 –

计算体积,我们必须返回 l*b*h

li>

要重载小于 (

当前对象的 l 是否与给定另一个对象的 l 不同,则

如果当前对象的l小于另一个对象的l,则返回true

否则,当当前对象的 b 与给定另一个对象的 b 不同时,则

如果当前对象的 b 较小,则返回 true比另一个对象的 b

否则,当当前对象的 h 与给定另一个对象的 h 不同时,则

如果当前对象的 h 小于另一个对象的 h,则返回 true

示例

让我们看看以下实现,以便更好地理解 –

#include using namespace std;class Box {    int l, b, h;public:    static int count;    Box() : l(0), b(0), h(0) { count++; }    Box(int length, int breadth, int height) : l(length), b(breadth), h(height) { count++; }    int getLength() const {return l;}    int getBreadth() const {return b;}    int getHeight() const {return h;}    long long CalculateVolume() const {        return 1LL * l * b * h;    }    bool operator<(const Box& another) const {        if (l != another.l) {            return l < another.l;        }        if (b != another.b) {            return b < another.b;        }        return h < another.h;    }};int Box::count = 0;int main(){    Box b1;    Box b2(5,8,3);    Box b3(6,3,8);    printf("Box 1: (length = %d, breadth = %d, width = %d)n",b1.getLength(), b1.getBreadth(), b1.getHeight());    printf("Box 2: (length = %d, breadth = %d, width = %d)n",b2.getLength(), b2.getBreadth(), b2.getHeight());    printf("Box 3: (length = %d, breadth = %d, width = %d)n",b3.getLength(), b3.getBreadth(), b3.getHeight());    if(b3 < b2){        cout << "Box 3 is smaller, its volume: " << b3.CalculateVolume() << endl;    }else{        cout << "Box 3 is smaller, its volume: " << b2.CalculateVolume() << endl;    }    cout << "There are total " << Box::count << " box(es)";}

输入

b1; b2(5,8,3); b3(6,3,8);

输出

Box 1: (length = 0, breadth = 0, width = 0)Box 2: (length = 5, breadth = 8, width = 3)Box 3: (length = 6, breadth = 3, width = 8)Box 3 is smaller, its volume: 120There are total 3 box(es)

以上就是C++程序创建盒子并计算体积,并使用小于运算符进行检查的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444095.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 21:00:09
下一篇 2025年12月12日 06:15:09

发表回复

登录后才能评论
关注微信