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
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (318)
      • 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(개발아님) (45)
        • Windows (25)
        • MacOS (7)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바