상속은 새로 정의된 클래스가 기존 클래스의 멤버 변수 및 함수(method)를 이용할 수 있게 해 준다.
즉, 클래스를 상속하여 다른 클래스에서 해당 클래스의 재사용을 가능하게 해 준다.
이때 상속해주는 기존 클래스를 상위 클래스 또는 부모 클래스라고 부르며,
기존 클래스로부터 상속을 받는 새롭게 정의된 클래스를 하위 클래스 또는 자식 클래스라고 부른다.
#include <iostream>
/****** superClass ******/
class Aircraft { // 상위 클래스(상속 해주는 클래스)
private:
bool isTakeOff;
double battery;
public:
void takeOff();
void land();
void print();
void chargeBattery(double);
};
/****** define functions of superClass ******/
void Aircraft::takeOff(){
isTakeOff = true;
battery = 50.0;
}
void Aircraft::land(){
isTakeOff = false;
}
void Aircraft::print(){ // 현재 상태 출력
if(isTakeOff ) {
std::cout << "TAKE OFF" << std::endl;
std::cout << "battery : " << battery << std::endl;
}
else {
std::cout << "LAND" << std::endl;
std::cout << "battery : " << battery << std::endl;
}
}
void Aircraft::chargeBattery(double num){ // 배터리 충전
battery += num;
if(battery >= 100.) battery = 100.; // max battery
}
/****** subClass ******/
class Drone : public Aircraft { // 하위 클래스 'Drone'을 선언하고,
// 상위 클래스 'Aircraft'를 상속하여 준다.
private:
public:
void charge(double);
};
/****** define functions of subClass ******/
void Drone::charge(double num){ // 배터리 충전
// battery = 100.; // 상위 클래스의 private에 접근할 수 없다.
chargeBattery(num); // 상위 클래스의 public method로 private에 접근한다.
}
/****** main ******/
int main(){
Drone MyDrone;
MyDrone.takeOff(); // 상위 클래스에 정의된 메소드를 사용할 수 있다.
MyDrone.print();
MyDrone.charge(10.0);
MyDrone.land();
MyDrone.print();
return 0;
}
/****** subClass ******/
// 상속받을 새로운 클래스(하위 클래스) 'Drone'을 선언한다.
// 그리고 상속할 기본 클래스(상위 클래스)를 'Aircraft'를 선언해준다.
class Drone : public Aircraft {
private:
public:
void charge(double);
};
/****** define functions of subClass******/
void Drone::charge(double num){
// 'Drone'의 상위 클래스 Aircraft::chargeBattery(int){}를 호출한다.
chargeBattery(num);
// battery += 10.0; // 하위 클래스에서 상위 클래스의 priavte에 접근할 수 없다.
// 대신 상위 클래스의 public에 선언된 멤버 함수를 호출하여 상위 클래스의 private에 접근할 수 있다.
}
/****** main ******/
int main(){
Drone MyDrone; // 객체 생성
// 하위 클래스에서 상의 클래스에 정의된 method를 사용할 수 있다.
MyDrone.takeOff(); // Aircraft::takeOff();
MyDrone.print(); // Aircraft::print();
MyDrone.charge(10.0); // Drone::charge(double);
MyDrone.land(); // Aircraft::land();
MyDrone.print();
return 0;
}
'C++' 카테고리의 다른 글
[C++] strncpy() (0) | 2019.12.06 |
---|---|
[C++] 오버로딩 (Overloading) 및 오버라이딩 (Overriding) (0) | 2019.11.21 |
[C++] malloc()-free() 와 new-delete (0) | 2019.11.16 |
[C++] 정적 할당(Static Allocation) 및 동적 할당(Dynamic Allocation) (0) | 2019.11.16 |
[C++] 오버플로우 (Overflow) (0) | 2019.11.05 |