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 There are total 3 box(es)
为了解决这个问题,我们将遵循以下步骤:
为了计算体积,我们需要返回 l*b*h
为了重载小于 (<) 运算符,我们需要检查
如果当前对象的 l 与给定另一个对象的 l 不相同,则
如果当前对象的 l 小于另一个对象的 l,则返回 true
否则,当当前对象的 b 与给定另一个对象的 b 不相同,则
如果当前对象的 b 小于另一个对象的 b,则返回 true
否则,当当前对象的 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)
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP