สร้างคลาส Box มีเงื่อนไข:
- แอตทริบิวต์ l, b, h (private)
- Constructor ไม่มีพารามิเตอร์ (ตั้งค่า 0) และมีพารามิเตอร์
- Getter สำหรับแต่ละแอตทริบิวต์
- CalculateVolume() คืนค่าปริมาตร
- โหลดโอเปอเรเตอร์ < เปรียบเทียบกล่อง
- ตัวนับจำนวนกล่องที่สร้าง (static count)
เช่น สร้าง 3 กล่อง (0,0,0), (5,8,3), (6,3,8) แสดงข้อมูล ตรวจสอบว่ากล่องที่ 3 เล็กกว่ากล่องที่ 2 ไหม หาปริมาตรกล่องเล็กกว่า และแสดงจำนวนกล่องทั้งหมด
ขั้นตอนการแก้ปัญหา
- CalculateVolume(): คืนค่า l*b*h
- โอเปอเรเตอร์ <: เปรียบเทียบ l ก่อน ถ้าเท่ากันเปรียบเทียบ b แล้วค่อย h
- static count เพิ่มใน constructor
ตัวอย่างโค้ด
#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)