假设我们必须定义一个具有很少条件的盒子类。如下 -
三个属性 l、b 和 h 分别表示长度、宽度和高度(这些是私有变量)
定义一个非参数化构造函数来将 l、b、h 设置为 0,并定义一个参数化构造函数来初始设置值。
定义每个属性的getter方法
定义一个函数calculateVolume()获取盒子的体积
重载小于运算符( <) 检查当前框是否小于另一个框。
创建一个可以计算创建的框数量的变量。
< /ul>
因此,如果我们输入三个框 (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: 120
There 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 <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: 120
There are total 3 box(es)