몇 가지 조건으로 상자 클래스를 정의해야 한다고 가정합니다. 다음과 같습니다 -
-
길이, 너비 및 높이에 대해 각각 l, b 및 h의 세 가지 속성이 있습니다(이들은 개인 변수임)
-
매개변수화되지 않은 생성자 하나를 정의하여 l, b, h를 0으로 설정하고 매개변수화 생성자 하나를 정의하여 초기에 값을 설정합니다.
-
각 속성에 대한 getter 메소드 정의
-
함수를 정의하십시오. CalculateVolume() 상자의 부피를 가져옵니다.
-
현재 상자가 다른 상자보다 작은지 확인하려면 보다 작음 연산자(<)를 오버로드하십시오.
-
생성된 상자의 개수를 셀 수 있는 변수를 만듭니다.
따라서 3개의 상자(0, 0, 0)(5, 8, 3), (6, 3, 8)에 대한 입력을 받아 각 상자 데이터를 표시하고 세 번째 상자가 두 번째 상자보다 작은지 확인하고, 작은 상자의 부피를 찾고 count 변수로 상자의 수를 인쇄합니다.
그러면 출력은
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)