C++ 상속 기본 예제

2021. 3. 19. 19:45·C++/Class

상속 기본 예제

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

  • 용어

    • 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
    */
저작자표시 (새창열림)

'C++ > Class' 카테고리의 다른 글

C++ 유도된 클래스들의 생성 순서  (0) 2021.03.19
C++ 상속 Teacher-Student 예제  (0) 2021.03.19
C++ 상속 (Inheritance)  (0) 2021.03.19
C++ 의존 관계 (Dependency)  (0) 2021.03.19
C++ 연계, 제휴 관계 (Association)  (0) 2021.03.19
'C++/Class' 카테고리의 다른 글
  • C++ 유도된 클래스들의 생성 순서
  • C++ 상속 Teacher-Student 예제
  • C++ 상속 (Inheritance)
  • C++ 의존 관계 (Dependency)
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 분류 전체보기 (317)
      • Algorithm (13)
        • 알기 쉬운 알고리즘 (10)
        • Search (1)
        • Sort (2)
      • Arduino (0)
      • C++ (185)
        • Class (46)
        • Exception (6)
        • Library (51)
        • Overloading (10)
        • SmartPointer (5)
        • Syntax (33)
        • TBC++ (23)
        • Templates (9)
        • VisualStudio (2)
      • Embedded (1)
      • Git (4)
      • Java (5)
      • Linux (16)
        • Error (1)
        • Linux Structure (11)
      • MacOS (7)
      • OS (1)
        • Concurrency (1)
      • Python (21)
        • Class (1)
        • Function (2)
        • Syntax (17)
      • Raspberrypi (9)
      • Review (1)
      • Utility (12)
        • VSCode (5)
        • VirtualBox (3)
      • Web (8)
        • Nginx (1)
        • React (3)
        • Django (1)
      • Windows (20)
        • Registry (3)
        • WSL (1)
        • DeviceDriver (6)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바