Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ tạo hộp, tính thể tích và so sánh bằng toán tử nhỏ hơn

Định nghĩa lớp Box với: thuộc tính private l, b, h; constructor mặc định và có tham số; getter cho từng thuộc tính; CalculateVolume(); nạp chồng toán tử < so sánh theo thứ tự l, b, h; biến static count đếm số hộp.

Ví dụ: b1(0,0,0), b2(5,8,3), b3(6,3,8). In thông tin, so sánh b3 < b2, in thể tích hộp nhỏ hơn, in tổng số hộp. Kết quả: Box 3 nhỏ hơn, thể tích 120, tổng 3 hộp.

Giải thuật

  • CalculateVolume(): return 1LL * l * b * h
  • operator<: so sánh l, nếu khác trả về l < other.l; tiếp theo b, cuối cùng h
  • Static count tăng trong constructor

Ví dụ minh họa

#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)"; 
} 

Đầu vào

b1; b2(5,8,3); b3(6,3,8);

Đầu ra

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)