본문 바로가기
Programming/C++

[ C++ ] 상속의 개념 | 상속 예제

by 코뮤(commu) 2021. 5. 18.
728x90
반응형

C++ 에서 상속이란?

 

클래스 사이에서의 상속관계를 정의하는 것이다.

 

기본 클래스의 속성과 기능을 파생 클래스에 물려주는 것이다.

 

+ 기본 클래스 -> 상속해주는 클래스. 부모 클래스

+ 파생 클래스 -> 상속받는 클래스. 자식 클래스

 

 

클래스를 상속하게 되면 얻는 이점

 

1. 클래스 간결하게 작성

 

2. 클래스 간의 계층적 분류 및 관리 용이

 

 

 

상속관계의 생성자와 소멸자 실행

 

 

질문 1:

 

파생 클래스의 객체가 새엇ㅇ될 때 파생 클래스의 생성자와 기본 클래스의 생성자가 모두 실행되나요?

 

답 1:

 

네 둘 다 실행됩니다.

 

 

질문 2:

 

파생 클래스의 생성자와 기본 클래스 생성자 중 어떤 생성자가 먼저 실행되나요?

 

답 2:

 

기본 클래스의 생성자가 먼저 실행됩니다.

 

 

 

#include <iostream>
using namespace std;
class TV {
int channel;
public:
    TV(int channel) { this->channel = channel; }
    TV() {}
    void on() { cout << channel << " On" << endl; }
    void off() { cout << " Off" << endl; }
    ~TV() { cout << "TV 소멸자" << endl; }
    int getChannel() { return channel; }
};
class ColorTV :public TV {
protected:   string color;
public:
    ColorTV(int channel, string color) :TV(channel) { this->color = color; }
    ColorTV() {}
    void show() { cout << color << "색 보여라" << endl; }
    ~ColorTV() { cout << "color TV 소멸" << endl; }
};
class SmartTv : public ColorTV {
    int price;
public:
    SmartTv() {}
    SmartTv(int channel, string color, int price) :ColorTV(channel, color) { this->price = price; }
    void replay() {
        cout << color << "색 채널번호 " << getChannel() << ", 가격 " << price
            << "원 입니다." << endl;
    }
};
class WideTV : public ColorTV {
private:
    int size;
public:
    WideTV(string color, int channel, int size);
    void play();
};
WideTV::WideTV(string color, int channel, int size) :ColorTV(channel, color) {
    this->size = size;

}
void WideTV::play() {
    cout << color << "색" << getChannel() << "번" << size << "인치" << endl;
}

int main() {
    TV t(7);
    t.on(); t.off();
    ColorTV ct(9, "RED");
    SmartTv sm(12, "Blue", 2500000);
    sm.replay();
    ct.show();
    ct.on();

    WideTV wt("Yello", 11, 60);
    wt.play();
}

 

 

 

728x90
반응형