728x90
상속에 대한 새로운 관점의 이해
"기존에 정의해 놓은 클래스의 재활용을 목적으로 만들어진 문법적 요소가 상속이다."
물론 상속에는 이러한 이점도 존재하지만, 이는 '상속'을 적용하는 근본적인 이유가 되지는 않는다.
상속은 재활용의 목적으로만 존재하는 문법적 요소가 아니다.
문제의 제시를 위한 시나리오의 도입
#include <iostream>
#include<cstring>
using namespace std;
class PermanentWorker {
private:
char name[100];
int salary;
public:
PermanentWorker(char* name, int money)
:salary(money)
{
strcpy(this->name, name);
}
int GetPay() const{
return salary;
}
void ShowSalaryInfo() const {
cout << "name: " << name << endl;
cout << "salary: " << GetPay() << endl << endl;
}
};
class EmployeeHandler {
private:
PermanentWorker* empList[50];
int empNum;
public:
EmployeeHandler() : empNum(0)
{ }
void AddEmployee(PermanentWorker* emp) {
empList[empNum++] = emp;
}
void ShowAllSalaryInfo() const {
for (int i = 0; i < empNum; i++) {
empList[i]->ShowSalaryInfo();
}
}
void ShowTotalSalary() const {
int sum = 0;
for (int i = 0; i < empNum; i++) {
sum += empList[i]->GetPay();
}
cout << "salary sum: " << sum << endl;
}
~EmployeeHandler() {
for (int i = 0; i < empNum; i++)
delete empList[i];
}
};
int main(void) {
//직원 관리를 목적으로 설계된 컨트롤 클래스의 객체 생성
EmployeeHandler handler;
//직원 등록
handler.AddEmployee(new PermanentWorker("KIM", 1000));
handler.AddEmployee(new PermanentWorker("LEE", 1500));
handler.AddEmployee(new PermanentWorker("JUN", 2000));
//이번 달에 지불해야 할 급여의 정보
handler.ShowAllSalaryInfo();
//이번 달에 지불해야 할 급여의 총 합
handler.ShowTotalSalary();
return 0;
}
Employeerhandler 클래스는 PermanentWorker클래스와 달리 기능적 성격이 강하다.
이렇게 기능의 처리를 실제로 담당하는 클래스를 가리켜 '컨트롤(control) 클래스' 또는 '핸들러(handler) 클래스'라 한다.
모든 소프트웨어의 설계에 있어서 중요한 것 중 하나는 다음과 같다.
- 요구사항의 변경에 대응하는 프로그램의 유연성
- 기능의 추가에 따른 프로그램의 확장성
문제의 제시
이전에는 직원의 고용 형태가 정규직 하나였는데, 영업직, 임시직이라는 새로운 고용형태가 등장했다고 가정하다.
위의 예제는 확장성에 있어서 좋지 않은 상태이다.
새로운 고용 형태에 대한 클래스의 추가로 인한 변경을 최소화할 수 있어야 하며,
EmployeeHandler클래스를 조금도 변경하지 않아도 된다면 더욱 좋다.
앞으로 공부할 '상속'을 적용하면 이러한 일들이 가능해진다.
728x90
'공부 > C++' 카테고리의 다른 글
[C++]7-3. protected 선언과 세가지 형태의 상속 (0) | 2024.11.07 |
---|---|
[C++] 7-2. 상속의 문법적인 이해 (0) | 2024.11.06 |
[C++] 6-3. c++에서의 static (2) | 2024.11.01 |
[C++] 6-2. 클래스와 함수에 대한 friend 선언 (0) | 2024.10.31 |
[C++] 6-1. const 보충 (0) | 2024.10.31 |