[C++] 운송수단을 객체로 구조체를 짜서 상속 및 벡터와 가상함수, 동적할당 쓰기
2022. 6. 15. 21:02ㆍ코딩 1막 <C++개념편>/코딩 1막 <C++응용편>
728x90
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Vehicle
{
string name;
int fuel;
Vehicle()
{
}
Vehicle(string _name, int _fuel)
{
name = _name;
fuel = _fuel;
}
void virtual PrintInfo()
{
cout << "운송수단 정보 : " << name << endl;
cout << "운송수단 연료정보 : " << fuel << endl;
}
virtual ~Vehicle()
{
cout << "운송수단 소멸자" << endl;
}
};
struct Car : Vehicle
{
int distance;
bool start = true;
Car()
{
}
Car(string _name, int _fuel, int _distance) : Vehicle(_name, _fuel)
{
name = _name;
fuel = _fuel;
distance = _distance;
}
void virtual PrintInfo()
{
cout << "차량 정보 : " << name << endl;
cout << "차량 연료정보 : " << fuel << "%" << endl;
cout << "차량 이동거리 : " << distance << "km" << endl;
}
void Drive(int oil)
{
fuel -= oil;
cout << name << "가 운전을 하면서 " << fuel << "만큼의 연료를 사용하였습니다" << endl;
if (fuel <= 0)
{
Off();
}
}
void Off()
{
cout << name << "가 연료가 소진되어 멈추었습니다" << endl;
start = false;
}
~Car()
{
cout << "차량 소멸자" << endl;
}
};
struct Boat : Vehicle
{
int distance;
bool start = true;
Boat()
{
}
Boat(string _name, int _fuel, int _distance) : Vehicle(_name, _fuel)
{
name = _name;
fuel = _fuel;
distance = _distance;
}
void virtual PrintInfo()
{
cout << "배 정보 : " << name << endl;
cout << "배 연료정보 : " << fuel << "%" << endl;
cout << "배 이동거리 : " << distance << "km" << endl;
}
void Drive(int oil)
{
fuel -= oil;
cout << name << "가 운전을 하면서 " << fuel << "만큼의 연료를 사용하였습니다" << endl;
if (fuel <= 0)
{
Off();
}
}
void Off()
{
cout << name << "가 연료가 소진되어 멈추었습니다" << endl;
start = false;
}
~Boat()
{
cout << "배 소멸자" << endl;
}
};
void main()
{
/*
Car carA("벤틀리", 10000, 100);
Car carB("람보르기니", 9000, 500);
Boat boatA("동백호", 8000, 600);
Boat boatB("타이타닉", 8000, 800);
vector<Vehicle> vehicleVec;
vehicleVec.push_back(carA);
vehicleVec.push_back(carB);
vehicleVec.push_back(boatA);
vehicleVec.push_back(boatB);
for (int i = 0; i < vehicleVec.size(); i++)
{
vehicleVec[i].PrintInfo();
}
*/
/*
vector<Vehicle*> vehicleVec;
vehicleVec.push_back(&carA);
vehicleVec.push_back(&carB);
vehicleVec.push_back(&boatA);
vehicleVec.push_back(&boatB);
*/
vector<Vehicle*> vehicleVec;
vehicleVec.push_back(new Car("벤틀리", 10000, 100));
vehicleVec.push_back(new Car("람보르기니", 9000, 500));
vehicleVec.push_back(new Boat("동백호", 8000, 600));
vehicleVec.push_back(new Boat("타이타닉", 8000, 800));
cout << "----------------------" << endl;
for (int i = 0; i < vehicleVec.size(); i++)
{
vehicleVec[i]->PrintInfo();
}
cout << "----------------------" << endl;
for (int i = 0; i < vehicleVec.size(); i++)
{
delete vehicleVec[i];
}
cout << "----------------------" << endl;
}
728x90
'코딩 1막 <C++개념편> > 코딩 1막 <C++응용편>' 카테고리의 다른 글
[C++] 상호참조를 할만한 두 구조체를 만들고 선언부와 구현부를 분리해보자 (0) | 2022.06.16 |
---|---|
[C++] 움직이는 자동차 시뮬레이션 (구조체, 벡터, 가상함수) (0) | 2022.06.15 |
[C++] 벡터를 사용해서 인벤토리 생성 (0) | 2022.06.14 |
[C++] 벡터를 사용해서 출석부만들기 (0) | 2022.06.14 |
[C++] 벡터의 기능을 이용해보자 (0) | 2022.06.14 |