使用小于运算符创建盒子并计算体积和检查的 C++ 程序
假设我们必须定义一个条件很少的盒子类。这些如下 -
长度、宽度和高度分别有 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: 120
共有 3 box(es)
示例
让我们看看以下实现以获得更好的理解 -
#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 << "共有 " << 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
共有 3 box(es)
以上是 使用小于运算符创建盒子并计算体积和检查的 C++ 程序 的全部内容, 来源链接: utcz.com/z/322672.html