假设我们必须定义一个具有很少条件的盒子类。如下 -
三个属性 l、b 和 h 分别表示长度、宽度和高度(这些是私有变量)
定义一个非参数化构造函数来将 l、b、h 设置为 0,并定义一个参数化构造函数来初始设置值。
定义每个属性的getter方法
定义一个函数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
要重载小于 (<) 运算符,我们必须检查
当前对象的 l 是否与给定另一个对象的 l 不同,则
如果当前对象的l小于另一个对象的l,则返回true
否则,当当前对象的 b 与给定另一个对象的 b 不同时,则
如果当前对象的 b 较小,则返回 true比另一个对象的 b
否则,当当前对象的 h 与给定另一个对象的 h 不同时,则
如果当前对象的 h 小于另一个对象的 h,则返回 true
示例让我们看看以下实现,以便更好地理解 -
#include <iostream>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++程序创建盒子并计算体积,并使用小于运算符进行检查的详细内容。