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
반응형
'Programming > C++' 카테고리의 다른 글
[ C++ ] 템플릿과 표준 템플릿 라이브러리(STL) (0) | 2021.06.09 |
---|---|
[ C++ ] 가상함수와 추상클래스 (0) | 2021.05.26 |
[ C++ ] 프렌드함수 || 연산자 중복 || 프렌드함수 예제, 연산자 중복 예제 (0) | 2021.05.11 |
[ C++ ] 함수 중복(Function Overloading) (0) | 2021.05.04 |
[ C++ ] 객체 포인터와 객체 - string 클래스 find() | C++ 행맨 게임 (0) | 2021.04.13 |