*자동차의 엔진을 인터페이스로 구현하여 결합도가 낮게 설계
더보기
더보기
#include <string>
#include <vector>
#include <iostream>
#include <memory>
using namespace std;
class Engine
{
public:
virtual void Start() = 0;
virtual ~Engine()
{
cout << "차의 모든 장치가 꺼집니다." << "\n\n";
}
};
class DieselEngine : public Engine
{
public:
void Start() override
{
cout << "디젤 엔진에 시동이 걸렸습니다." << endl;
}
~DieselEngine() override
{
cout << "디젤 엔진에 시동이 꺼졌습니다." << endl;
}
};
class ElectricEngine : public Engine
{
public:
void Start() override
{
cout << "전기 엔진에 시동이 걸렸습니다." << endl;
}
~ElectricEngine() override
{
cout << "전기 엔진에 시동이 꺼졌습니다." << endl;
}
};
class Car
{
private:
unique_ptr<Engine> EngineRef;
public:
Car(unique_ptr<Engine> engine) : EngineRef(move(engine)) {}
void StartCar()
{
EngineRef->Start();
cout << "주행을 시작합니다." << endl;
}
~Car()
{
cout << "주행을 종료합니다." << endl;
}
};
int main()
{
// FirstCar의 스코프를 제한
{
Car FirstCar(make_unique<DieselEngine>());
FirstCar.StartCar();
}
// SecondCar의 스코프를 제한
{
Car SecondCar(make_unique<ElectricEngine>());
SecondCar.StartCar();
}
}
- 클래스에 순수 가상함수가 있다면 그것을 추상 클래스라고 했었는데, 인터페이스라고도 부른다.
- 부모클래스의 포인터로 자식 클래스를 관리할 때, 가상 소멸자를 꼭 명시해줘야 자식클래스의 소멸자도 호출이 된다.
- 가상 소멸자로 명시해주지 않으면, 기본 소멸자로 내부적으로 생성하기 때문에 이 역시 자식클래스의 소멸자는 호출되지 않는다.
- 소멸자의 호출 순서는 생성된 순서의 역순이다.
- 만약 객체의 생성과 소멸을 조정하려면 스코프를 제한하는 방법도 있다. { } 이것이 스코프.
'내배캠 > C++' 카테고리의 다른 글
std::toupper / std::tolower (0) | 2024.12.30 |
---|---|
비트 연산자 (0) | 2024.12.30 |
std::rand / std::srand / std::time (0) | 2024.12.26 |
std::fixed / std::setprecision (0) | 2024.12.26 |
std::cin::fail / std::cin::clear / std::cin::ignore (0) | 2024.12.26 |