[열혈 c++ 프로그래밍] ch7

hyng·2023년 3월 18일
0

열혈 c++ 프로그래밍을 보고 요약정리합니다.

7-1 상속에 들어가기에 앞서

  • 문제 제시를 위한 시나리오 도입
    • 급여관리 시스템
      - 모든 직원은 정규직
      - 정규직 급여는 입사 당시 정해진다. (인상부분은 고려하지 x)

      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];
              }
          }
      };
    • 요구사항의 변경에 대응하는 프로그램의 유연성, 기능의 추가에 따른 프로그램의 확장성이 중요하다.

  • 여러 직원 고용형태가 나오게 된다면?
    • 직원은 각각 급여 계산방식에서 차이가 있기 때문에 별도의 클래스를 생성한다고 하자.
      • 영업직(SalesMan), 임시직(Temporary)

      • EmployeeHandler에도 각 클래스 배열을 만들어주어야 한다.

      • AddEmployee 함수는 SalesMan 객체용과 Temporary 객체용으로 각각 추가되어야 하고, 급여정보를 출력하는 나머지 두 멤버 함수는 총 3개의 배열을 대상으로 연산을 진행해야 하니까 반복문이 추가로 각각 두개씩 더 삽입되어야 한다.

        → 요구사항 하나가 추가되자 기존 코드에 많은 부분이 달라졌다.

7-2 상속의 문법적인 이해

  • 상속을 하게 되면, 상속의 대상이 되는 클래스의 멤버까지도 객체 내에 포함된다.
    • 유도클래스를 생성하면 기초클래스의 생성자가 먼저 호출된다.

    • 문제 07-1

      class Car
      {
      private:
          int gasolineGauge;
      public:
          Car(int gasolineGauge) : gasolineGauge(gasolineGauge)
          {
      
          }
          int GetGasGauge()
          {
              return gasolineGauge;
          }
      };
      class HybridCar : public Car
      {
      private:
          int electricGauge;
      public:
          HybridCar(int gasolineGauge, int electricGauge) : Car(gasolineGauge), electricGauge(electricGauge)
          {
      
          }
          int GetElectricGauge()
          {
              return electricGauge;
          }
      };
      
      class HybridWaterCar : public HybridCar
      {
      private:
          int waterGauge;
      public:
          HybridWaterCar(int waterGauge, int gasolineGauge, int electricGauge) : HybridCar(gasolineGauge, electricGauge), waterGauge(waterGauge)
          {
      
          }
          void ShowCurrentGauge()
          {
              cout << "잔여 가솔린: " << GetGasGauge() << endl;
              cout << "잔여 전기량: " << GetElectricGauge() << endl;
              cout << "잔여 워터량: " << waterGauge << endl;
          }
      };
      
      class MyFriendInfo
      {
      private:
          char * name;
          int age;
      public:
          MyFriendInfo(char * name, int age)
          {
              this->age = age;
              strcpy(this->name, name);
          }
          void ShowMyFriendInfo()
          {
              cout << "이름: " << name << endl;
              cout << "나이: " << age << endl;
          }
      };
      
      class MyFriendDetailInfo : public MyFriendInfo
      {
      private:
          char * addr;
          char * phone;
      public:
          MyFriendDetailInfo(char * name, int age, char * addr, char * phone) : MyFriendInfo(name, age)
          {
              strcpy(this->addr, addr);
              strcpy(this->phone, phone);
          }
          void ShowMyFriendDetailInfo()
          {
              ShowMyFriendDetailInfo();
              cout << "주소: " << addr << endl;
              cout << "전화: " << phone << endl << endl;
          }
      };

7-3 protected 선언과 세 가지 형태의 상속

  • c++ 접근 제어자: public, protected, private
    • public > protected > private
  • protected 상속
    • protected보다 접근의 범위가 넓은 멤버는 protected로 변경시켜서 상속
  • private 상속
    • private보다 접근의 범위가 넓은 멤버는 private로 변경시켜서 상속
  • public 상속
    • public보다 접근의 범위가 넓은 멤버는 public로 변경시켜서 상속

7-4 상속을 위한 조건

  • IS-A 관계의 성립
    • 상속관계가 성립하려면 기초 클래스와 유도 클래스간에 IS-A 관계가 성립해야 한다.
      • ex. 무선전화기 ↔ 전화기, 노트북 컴퓨터 ↔ 컴퓨터
  • HAS-A 관계
    • HAS-A 관계도 상속의 조건은 되지만 복합 관계로 이를 대신하는 것이 일반적이다.
    • 상속으로 묶인 두 개의 클래스는 강한 연관성을 띤다.
      • Gun 클래스를 상속하는 Police 클래스로는 총을 소유하는 경찰만 표현가능하다.
      • 만약 전기봉을 소유한 경찰을 표현해야 한다면?
        • 전기봉을 나타내는 클래스를 생성하고 Police 클래스가 다중 상속하도록 처리해야 하나?
          • 복잡한 다중 상속
      • 만약 총을 소유하지 않는 경찰도 표현해야 한다면?

문제 7-2

  • 1
    class Rectangle
    {
    private:
        int row;
        int col;
    public:
        Rectangle(int row, int col)
        {
            this->row = row;
            this->col = col;
        }
        void ShowAreaInfo()
        {
            cout << "면적: " << row * col << endl;
        }
    };
    
    class Square : public Rectangle
    {
    public:
        Square(int len) : Rectangle(len, len)
        {
    
        }
    };
  • 2
    class Book
    {
    private:
        char * title;
        char * isbn;
        int price;
    public:
        Book(char * title, char * isbn, int price)
        {
            this->title = new char[::strlen(title) + 1];
            this->isbn = new char[strlen(isbn) + 1];
            ::strcpy(this->title, title);
            ::strcpy(this->isbn, isbn);
            this->price = price;
        }
        void ShowBookInfo()
        {
            cout << "제목: " << title << endl;
            cout << "ISBN: " << isbn << endl;
            cout << "가격: " << price << endl;
        }
    };
    class EBook : public Book
    {
    private:
        char * DBMKey;
    public:
        EBook(char * title, char * isbn, int price, char * DBMKey) : Book(title, isbn, price)
        {
            this->DBMKey = new char[strlen(DBMKey) + 1];
            ::strcpy(this->DBMKey, DBMKey);
        }
        void ShowEBookInfo()
        {
            Book::ShowBookInfo();
            cout << "인증키: " << DBMKey << endl;
        }
    };
    int main() {
        Book book("좋은 C++", "555-12345-890-0", 20000);
        book.ShowBookInfo();
        cout << endl;
        EBook ebook("좋은 c++ ebook", "555-12345-890-1", 10000, "fdx9w0i8kiw");
        ebook.ShowEBookInfo();
        return 0;
    }
profile
공부하고 알게 된 내용을 기록하는 블로그

0개의 댓글