반응형
namespace 활용
#include <iostream>
using namespace std;
namespace CAR_CONST
{
enum
{
ID_LEN = 20,
MAX_SPD = 200,
FUEL_STEP = 2,
ACC_STEP = 10,
BRK_STEP = 10
};
}
struct Car
{
char gamerID[CAR_CONST::ID_LEN];
int fuelGauge;
int curSpeed;
void ShowCarState()
{
cout << "소유자ID: " << gamerID << endl;
cout << "연료량: " << fuelGauge << "%" << endl;
cout << "현재속도:" << curSpeed << "km/s" << endl << endl;
}
void 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 Break()
{
if (curSpeed < CAR_CONST::BRK_STEP)
{
curSpeed = 0;
return;
}
curSpeed -= CAR_CONST::BRK_STEP;
}
};
int main()
{
Car run99 = { "run99",100,0 };
run99.Accel();
run99.Accel();
run99.ShowCarState();
run99.Break();
run99.ShowCarState();
Car sped77 = { "sped77",100,0 };
sped77.Accel();
sped77.Break();
sped77.ShowCarState();
return 0;
}
구조체내의 함수 예제
#include <iostream>
using namespace std;
#define ID_LEN 20
#define MAX_SPD 200
#define FUEL_STEP 2
#define ACC_STEP 10
#define BRK_STEP 10
struct Car
{
char gamerID[ID_LEN];
int fuelGauge;
int curSpeed;
void ShowCarState()
{
cout << "소유자ID: " << gamerID << endl;
cout << "연료량: " << fuelGauge << "%" << endl;
cout << "현재속도:" <<curSpeed << "km/s" << endl << endl;
}
void Accel()
{
if (fuelGauge <= 0)
return;
else
fuelGauge -= FUEL_STEP;
if (curSpeed + ACC_STEP >= MAX_SPD)
{
curSpeed = MAX_SPD;
return;
}
curSpeed += ACC_STEP;
}
void Break()
{
if (curSpeed < BRK_STEP)
{
curSpeed = 0;
return;
}
curSpeed -= BRK_STEP;
}
};
int main()
{
Car run99 = { "run99",100,0 };
run99.Accel();
run99.Accel();
run99.ShowCarState();
run99.Break();
run99.ShowCarState();
Car sped77 = { "sped77",100,0 };
sped77.Accel();
sped77.Break();
sped77.ShowCarState();
return 0;
}
Chapter3 문제 03-1
#define _CRT_SECURE_NO_WANRINGS
#include <iostream>
using namespace std;
struct Point
{
int xpos;
int ypos;
void MovePos(int x, int y)
{
xpos += x;
ypos += y;
}
void AddPoint(const Point& pos)
{
xpos += pos.xpos;
ypos += pos.ypos;
}
void ShowPosition()
{
cout << "[" << xpos << "," << ypos << "]" << endl;
}
};
int main()
{
Point pos1 = { 12,4 };
Point pos2 = { 20,30 };
pos1.MovePos(-7, 10);
pos1.ShowPosition();
pos1.AddPoint(pos2);
pos1.ShowPosition();
return 0;
}
반응형
'Programming > C++' 카테고리의 다른 글
c++ call-by-reference , 열혈c++ Chapter2 문제1, 문제3, 문제02-2 (0) | 2021.08.15 |
---|---|
열혈 c++ Chapter02 문제02-3 , 02-4 문제1 , 문제2, Chapter03 예제 (참조자,상수값) (0) | 2021.08.15 |
열혈c++ Chapter03 문제03-2 1번 2번 (0) | 2021.08.15 |
열혈c++ 문제 4-1 , 4-2 (0) | 2021.08.15 |
열혈c++ Chapter 04 문제04-3 (0) | 2021.08.15 |