C++ 상속 기본 예제

2021. 3. 19. 19:45·SW개발/C++
반응형

상속 기본 예제

  • 상속의 본질은 일반화이다.

  • 용어

    • Generalized class : 상속하는 상위 클래스

    • Derived class : 상속을 받은 하위 클래스

  • 예제

    #include <iostream>
    
    using namespace std;
    
    class Mother
    {
      int    i_;
    
    public:
      Mother(const int& i_in = 0)
        : i_{ i_in }
      {
        cout << "Mother Constructor\n";
      }
    
      void        setValue(const int& i_in)
      {
        i_ = i_in;
      }
    
      int        getValue()
      {
        return i_;
      }
    };
    
    class Child : public Mother
    {
      double    d_;
    
    public:
      Child(const int & i_in = 0, const double & d_in = 0)
        //: i_{i_in}, d_{d_in}  // 생성자 호출 순서때문에 불가능
      {
        cout << "Child Constructor\n";
        Mother::setValue(i_in);
        d_ = d_in;
      }
    
      void        setValue(const int& i_in, const double& d_in)
      {
        Mother::setValue(i_in);
        d_ = d_in;
      }
    
      void        setValue(const double& d_in)
      {
        d_ = d_in;
      }
    
      double    getValue()
      {
        return d_;
      }
    };
    
    class Daughter : public Mother  // 여러 클래스로 상속할 수 있다.
    {
    
    };
    
    class Son : public Mother
    {
    
    };
    
    int        main()
    {
      Mother mother(120);
      mother.setValue(1024);
      cout << mother.getValue() << endl;
    
      Child child;
      child.Mother::setValue(987);
      cout << child.Mother::getValue() << endl;
    
      child.setValue(128);
      cout << child.getValue() << endl;
    }
    
    /* stdout
    Mother Constructor
    1024
    Mother Constructor
    Child Constructor
    987
    128
    */
    • 중간 주석 부분을 제거하고 빌드해보면 i_{i_in}에서 오류가 발생한다.

      error C2614: 'Child': illegal member initialization: 'i_' is not a base or member
      • VS에서 마우스를 갖다대면 inaccessible 상태로 나오지만, 접근 지정자 문제는 아니다.

      • 부모 클래스의 생성자를 호출하기 전에 i_ 변수에 접근하려해서 발생하는 오류라고 한다.

      • 이를 해결할 때는 아래와 같이 부모 클래스의 생성자를 활용하는 편인 것 같다.


  • 다음과 같이 부모 클래스의 생성자를 위임 생성자처럼 사용하는게 정석같은 느낌이다.

    #include <iostream>
    
    using namespace std;
    
    class Mother
    {
      int    i_;
    
    public:
      Mother(const int& i_in = 0)
        : i_{ i_in }
      {
        cout << "Mother Constructor\n";
      }
    
      void    setValue(const int& i_in)
      {
        i_ = i_in;
      }
    
      int        getValue()
      {
        return i_;
      }
    };
    
    class Child : public Mother
    {
      double    d_;
    
    public:
      Child(const int & i_in = 0, const double & d_in = 0)
        : Mother(i_in), d_{d_in}
      {
        cout << "Child Constructor\n";
      }
    
      void    setValue(const int& i_in, const double& d_in)
      {
        Mother::setValue(i_in);
        d_ = d_in;
      }
    
      void    setValue(const double& d_in)
      {
        d_ = d_in;
      }
    
      double    getValue()
      {
        return d_;
      }
    };
    
    int        main()
    {
      Mother mother(120);
      mother.setValue(1024);
      cout << mother.getValue() << endl;
    
      Child child;
      child.Mother::setValue(987);
      cout << child.Mother::getValue() << endl;
    
      child.setValue(128);
      cout << child.getValue() << endl;
    }
    
    /* stdout
    Mother Constructor
    1024
    Mother Constructor
    Child Constructor
    987
    128
    */
반응형
저작자표시 (새창열림)

'SW개발 > C++' 카테고리의 다른 글

C++ 유도된 클래스들의 생성 순서  (0) 2021.03.19
C++ 상속 Teacher-Student 예제  (0) 2021.03.19
C++ 상속 (Inheritance)  (0) 2021.03.19
따라하며 배우는 C++ 11장  (0) 2021.03.19
C++ IntArray  (0) 2021.03.19
'SW개발/C++' 카테고리의 다른 글
  • C++ 유도된 클래스들의 생성 순서
  • C++ 상속 Teacher-Student 예제
  • C++ 상속 (Inheritance)
  • 따라하며 배우는 C++ 11장
Caniro
Caniro
MinimalismCaniro 님의 블로그입니다.
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (319)
      • SW개발 (268)
        • Java Spring (6)
        • C++ (186)
        • Python (21)
        • Linux (16)
        • 알고리즘 (13)
        • Git (4)
        • Embedded (1)
        • Raspberrypi (9)
        • React (3)
        • Web (2)
        • Windows Device Driver (6)
      • IT(개발아님) (46)
        • Windows (26)
        • MacOS (7)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    맥북 카카오톡 알림 안뜸
    vscode
    백기선
    Workspace
    spring
    dism
    unix
    SFC
    citrix workspace
    java
    스프링 프레임워크 핵심 기술
    SunOS 5.1
    제외
    윈도우 명령어
    스프링
    시스템 복구
    알림
    logi options
    mspaint
    로지텍 마우스 제스처
    EXCLUDE
    Solaris 10
    윈도우
    Windows 11
    그림판
    MacOS
    windows
    KakaoTalk
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ 상속 기본 예제

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.