PowerC++ 문제풀이, Chapter 10, Programming 2번
#include<iostream>
using namespace std;
// 클래스 선언
class Box
{
private:
double height, length, width;
bool isEmpty;
public:
// 생성자
Box(); // 디폴트 생성자
Box(double w, double l, double h); // 명시적 생성자 중복 정의
// setter
void setHeight(double h);
void setLength(double l);
void setWidth(double w);
void setEmpty(bool e);
// getter
double getHeight();
double getWidth();
double getLength();
// 멤버 함수
void print();
double getVolume();
void empty();
};
// main 함수
int main()
{
double vb1, vb2, vb3;
Box b1(3.5, 4.4, 5.0), b2, b3;
b3.setHeight(4.0);
b3.setLength(5.0);
b3.setWidth(2.4);
cout << "========================================" << endl;
cout << "박스 1 "; b1.print();
cout << "박스 2 "; b2.print();
cout << "박스 3 "; b3.print();
cout << "========================================" << endl;
// 2번 문제 empty 함수 추가
b3.setEmpty(0);
b1.empty();
b2.empty();
b3.empty();
cout << endl;
vb1 = b1.getVolume();
vb2 = b2.getVolume();
vb3 = b3.getVolume();
if (vb1 > vb2) {
if (vb1 > vb3)
cout << "박스1의 부피가 가장 큽니다 : " << vb1;
else
cout << "박스3의 부피가 가장 큽니다 : " << vb3;
}
else {
if (vb2 > vb3)
cout << "박스2의 부피가 가장 큽니다 : " << vb2;
else
cout << "박스3의 부피가 가장 큽니다 : " << vb3;
}
cout << endl;
return 0;
}
// 클래스 구현
// 생성자
Box::Box() { //디폴트 생성자
width = 10;
length = 10;
height = 10;
isEmpty = true;
}
Box::Box(double w, double l, double h) { // 명시적 생성자 중복 정의
// 2-1 문항에 의거 디폴트 매개변수는 지정하지 않음.
// 과제에는 if문 사용하지 않았음.
if (w < 0)
w = 1;
if (l < 1)
l = 1;
if (h < 1)
h = 1;
width = w, length = l, height = h, isEmpty = true;
}
// setter
void Box::setHeight(double h) {
height = h;
}
void Box::setLength(double l) {
length = l;
}
void Box::setWidth(double w) {
width = w;
}
void Box::setEmpty(bool e) {
isEmpty = e;
}
// getter
double Box::getHeight() {
return height;
}
double Box::getWidth() {
return width;
}
double Box::getLength() {
return length;
}
// 멤버 함수
void Box::print() {
cout << "부피는 : " << width * length * height << endl;
}
double Box::getVolume() {
return width * length * height;
}
void Box::empty() {
cout << "이 상자는 ";
if (isEmpty == true)
cout << "비어있습니다.";
else
cout << "물건이 들어있습니다.";
cout << endl;
}