[열혈강의c++]8장 상속과 다형성

음...C++에서 중요한건 클래스의 확장성을 고려해서 만들어야 된다..
이럴려면 제목처럼 상속과 다형성에 대해서 알아봐야하는데 ...밑에 그림을 보자.

저기서 보면 간단한 클래스를 상속의 개념을 덧붙여 그리고 있다
어떠한 문제냐면 간단히 Department라는 클래스가 일용직이든 고용직이든 모든 기능을
수행하는 클래스이고 일용직이나 고용직 클래스는 그것을 상속하고 있다
하지만 회사가 커져버려서 판매직이라던지 마케팅 등등 여러 부서가 만들어지고
클래스를 확장을 해야한다 하지만 위처럼 구현된다면 부서가 만들어 질때마다
Department class를 변경해야하는 수고스러움이 있다 그래서
가령 일용직이나 고용직의 공통된 분모를 뽑아 Employee라는 클래스를 만들고
이 클래스는 두개의 고용직을 상속당하는 형태이고 이 Emplyee클래스는
Department에 상속이 되어진다...
그리고 객체를 만듬에 있어서 포인터 값으로(참조...)형태를 만든다 코드는 아래와 같다..
#include <iostream>

using std::cout;
using std::endl;

class Employee
{
protected:
 char name[20];
public:
 Employee(char *_name);
 const char *GetName();

};
Employee::Employee(char *_name)
{
 strcpy(name,_name);
}
const char *Employee::GetName()
{
 return name;
}
/* Permanet class 급여관리 */
class Permanent:public Employee
{
private:
 int salary;
public:
 Permanent(char *_name,int sal);
 int GetPay();
};

Permanent::Permanent(char *_name,int sal)
: Employee(_name)
{
 salary=sal;
}
int Permanent::GetPay()
{
 return salary;
}
/* Tmeporary class */
class Temporary : public Employee
{
private:
 int time;
 int pay;
public:
 Temporary(char *_name,int _time,int _pay);
 int GetPay();
};
Temporary::Temporary(char *_name,int _time,int _pay)
: Employee(_name)
{
 time = _time;
 pay = _pay;
}
int Temporary::GetPay()
{
 return time*pay;
}
class Department
{
private:
 Employee *empList[10];
 int index;
public:
 Department():index(0){};
 void AddEmployee(Employee *emp);
 void ShowList();
};
void Department::AddEmployee(Employee *emp)
{
 empList[index++]=emp;
}
void Department::ShowList()
{
 for(int i=0; i<index ;i++){
  cout<<"name : "<<empList[i]->GetName()<<endl;
  cout<<"sal : "<<empList[i]->GetPay()<<endl;//error
  cout<<endl;
 }
}

int main()
{
 Department department;

 department.AddEmployee(new Permanent("KIM",1000));
 department.AddEmployee(new Permanent("LEE",1500));
 department.AddEmployee(new Temporary("HAN",10,200));
 department.AddEmployee(new Temporary("JANG",12,1000));

 department.ShowList();
 return 0;
}
소스코드중 cout<<"sal : "<<empList[i]->GetPay()<<endl;//error
여기 부분은 에러가 된다 이유는 이 empList라는 배열은 employee클래스의 포인터들을 담고있다
이 employee클래스의 포인터들은 결과적으로 일용직,고용직의 클래스들을 포함하는 형태(맨위 그림참조)
이므로 멤버함수를 쓸수 있지 않을까?라고 하지만...
이것은 8장 앞에서 애기 했듯이 상속하는 클래스는 결과적으로 상속된 모든 멤버들을 가져오므로
객체크기를 비교했을때 제일 나중에 상속 받는 클래스는 크게 된다.
이때의 과정은 간단히 말하면
A->B->C (화살표는 상속되는 순서)
이것은 메모리상으로 A가 가장 작은 녀석이고 B가 그담 C가 젤크다...
클래스를 포인터로 했을때 접근을 보자면
C의 클래스 포인터는 A,B,C의 멤버함수를 쓸수 있고 B의 클래스 포인터는 A,B의 멤버함수를 쓸수 있으며
A의 클래스 포인터는 자신의 멤버함수만을 쓸수 밖에 없어서
empList[i]->GetPay()는 에러가 나게된다..
이에 해결책은 다음 시간에...~_~

이 글과 관련있는 글을 자동검색한 결과입니다 [?]

by 홍텐 | 2008/04/24 00:48 | c++ | 트랙백 | 덧글(2)

트랙백 주소 : http://HongTen.egloos.com/tb/1639878
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]
Commented by JOKER at 2008/05/27 23:31
안녕하세요~
KoreaSec의 프리 입니다. ELF 강좌 잘 보고 갑니다 ~~
자주는 모르겠지만 많이 올께요 >_<
Commented at 2008/07/15 14:08
비공개 덧글입니다.
※ 로그인 사용자만 덧글을 남길 수 있습니다.

◀ 이전 페이지다음 페이지 ▶