[문제]
아래의 코드를 가지고 Car.h, Car.cpp, RacingMain.cpp로 파일을 나눠라.
#include <iostream>
#include <cstring>
using namespace std;
namespace CAR_CONST
{
enum
{
ID_LEN = 20, MAX_SPD = 200, FUEL_STEP = 2,
ACC_STEP = 10, BRK_STEP = 10
};
}
class Car
{
private:
char gamerID[CAR_CONST::ID_LEN];
int fuelGauge;
int curSpeed;
public:
void InitMembers(const char* ID, int fuel);
void ShowCarState();
void Accel();
void Break();
};
void Car::InitMembers(const char* ID, int fuel)
{
strcpy(gamerID, ID);
fuelGauge = fuel;
curSpeed = 0;
}
void Car::ShowCarState()
{
cout << "소유자ID: " << gamerID << endl;
cout << "연료량: " << fuelGauge << "%" << endl;
cout << "현재 속도: " << curSpeed << "km/s" << endl << endl;
}
void Car::Accel()
{
if (fuelGauge <= 0)
return;
else
fuelGauge -= CAR_CONST::FUEL_STEP;
if ((curSpeed + CAR_CONST::ACC_STEP) >= CAR_CONST::MAX_SPD)
{
curSpeed = CAR_CONST::MAX_SPD;
return;
}
curSpeed += CAR_CONST::ACC_STEP;
}
void Car::Break()
{
if (curSpeed < CAR_CONST::BRK_STEP)
{
curSpeed = 0;
return;
}
curSpeed -= CAR_CONST::BRK_STEP;
}
int main()
{
Car run99;
run99.InitMembers("run99", 100);
run99.Accel();
run99.Accel();
run99.Accel();
run99.ShowCarState();
run99.Break();
run99.ShowCarState();
return 0;
}
[실행 결과]
소유자ID: run99
연료량: 94%
현재속도: 30km/s
소유자ID: run99
연료량: 94%
현재속도: 20km/s
[코드]
1. Car.h
#ifndef __CAR_H__
#define __CAR_H__
namespace CAR_CONST
{
enum
{
ID_LEN = 20, MAX_SPEED = 200, FUEL_STEP = 2,
ACC_STEP = 10, BREAK_STEP = 10
};
}
class Car
{
private:
char gamerID[CAR_CONST::ID_LEN];
int fuelGauge;
int curSpeed;
public:
void InitMembers(const char* ID, int fuel);
void ShowCarState();
void Accel();
void Break();
};
#endif
2. Car.cpp
#include<iostream>
#include<cstring>
#include "Car.h"
using namespace std;
void Car::InitMembers(const char* ID, int fuel)
{
strcpy(gamerID, ID);
fuelGauge = fuel;
curSpeed = 0;
}
void Car::ShowCarState()
{
cout << "소유자ID: " << gamerID << endl;
cout << "연료량: " << fuelGauge << "%" << endl;
cout << "현재속도: " << curSpeed << "km/s" << endl << endl;
}
void Car::Accel()
{
if (fuelGauge <= 0)
return;
else
fuelGauge -= CAR_CONST::FUEL_STEP;
if (curSpeed >= CAR_CONST::MAX_SPEED)
{
curSpeed = CAR_CONST::MAX_SPEED;
return;
}
curSpeed += CAR_CONST::ACC_STEP;
}
void Car::Break()
{
if (curSpeed < CAR_CONST::BREAK_STEP)
curSpeed = 0;
curSpeed -= CAR_CONST::BREAK_STEP;
}
3. RacingMain.cpp
#include "Car.h"
int main()
{
Car run99;
run99.InitMembers("run99", 100);
run99.Accel();
run99.Accel();
run99.Accel();
run99.ShowCarState();
run99.Break();
run99.ShowCarState();
return 0;
}
<참고>
윤성우의 열혈 C++ 프로그래밍
'C++ 언어 > 연습문제' 카테고리의 다른 글
C++ 언어 연습문제13 (0) | 2022.09.28 |
---|---|
C++ 언어 연습문제12 (0) | 2022.09.27 |
C++ 언어 연습문제10 (0) | 2022.09.26 |
C++ 언어 연습문제9 (0) | 2022.08.14 |
C++ 언어 연습문제8 (0) | 2022.08.08 |