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