สมมติว่าเราจะต้องกำหนดคลาสกล่องที่มีเงื่อนไขเล็กน้อย ดังต่อไปนี้ −
-
มีสามแอตทริบิวต์ l, b และ h สำหรับความยาว ความกว้าง และความสูงตามลำดับ (เป็นตัวแปรส่วนตัว)
-
กำหนดคอนสตรัคเตอร์ที่ไม่มีพารามิเตอร์หนึ่งตัวเพื่อตั้งค่า l, b, h เป็น 0 และคอนสตรัคเตอร์หนึ่งตัวเพื่อตั้งค่าเริ่มต้น
-
กำหนดวิธี getter สำหรับแต่ละแอตทริบิวต์
-
กำหนดฟังก์ชัน calcVolume() รับปริมาตรของกล่อง
-
โอเวอร์โหลดน้อยกว่าโอเปอเรเตอร์ (<) ให้ติ๊กเลือกช่องปัจจุบันว่าน้อยกว่าช่องอื่นหรือไม่
-
สร้างตัวแปรที่สามารถนับจำนวนช่องที่สร้างขึ้นได้
ดังนั้น หากเราใส่ข้อมูลสำหรับสามช่อง (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 ของวัตถุอื่น
-
-
มิฉะนั้นเมื่อ b ของวัตถุปัจจุบันไม่เหมือนกับ b ของวัตถุอื่นที่ให้มา
-
คืนค่า จริง หาก b ของวัตถุปัจจุบันมีขนาดเล็กกว่า b ของวัตถุอื่น
-
-
มิฉะนั้นเมื่อ h ของวัตถุปัจจุบันไม่เหมือนกับ h ของวัตถุอื่น ดังนั้น
-
คืนค่า จริง หาก h ของวัตถุปัจจุบันน้อยกว่า h ของวัตถุอื่น
-
ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#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)