struct안에 함수를 선언하면 .(점) 연산자로 해당 함수에 접근이 가능하다.
#define LEN 10
#define FUEL 2
#define ACC 10
#define MAX 200
#define BREAK 10
struct Car
{
char id[LEN];
int fuel;
int speed;
void show()
{
cout << "ID : " << id << endl;
cout << "연료량 : " << fuel << endl;
cout << "속도 : " << speed << endl;
}
void accel()
{
if (fuel <= 0)
return;
else
fuel -= FUEL;
if (speed + ACC >= MAX)
{
speed = MAX;
return;
}
speed += ACC;
}
void Break()
{
if (speed < BREAK)
{
speed = 0;
return;
}
speed -= BREAK;
}
};
int main()
{
Car run99 = { "run99", 100, 0 }; //run99 이름의 객체 생성
run99.accel(); // 100에서 연료 깎기
run99.accel();
run99.show();
run99.Break(); //speed = 0
run99.show();
Car speed77 = { "speed77", 100, 0 };
speed77.accel();
speed77.Break();
speed77.show();
}
문제 03-1
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(); // [5,14] 출력
pos1.AddPoint(pos2);
pos1.ShowPosition(); // [25,44] 출력
return 0;
}
- 접근 제어 지시자
public : 어디서든 접근 허용
protected : 상속 관계에 놓여있을 때, 유도 클래스에서의 접근 허용
private : 클래스 내에서만 접근 허용
#include <iostream>
#include <cstring>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
namespace CAR
{
enum {
ID = 20, MAX = 200, FUEL = 2,
ACC = 10, BRK = 10
};
} //CAR이라는 이름의 네임스페이스를 만들어서 #define 대체
class Car
{
private : //private 객체 선언 (class 안에서만 사용이 가능하다)
char gameID[CAR::ID];
int fuelGauge;
int speed;
public:
void InitMembers(char* id, int fuel); //public 함수 선언 (클래스 밖에서도 사용 가능)
void show();
void accel();
void Break();
};
// 함수 정의 (Car 네임스페이스 안에서 선언해야 상수 사용 가능
void Car::InitMembers(char* id, int fuel)
{
strcpy(gameID, id); //클래스 내부의 함수이기 때문에 private 객체를 사용할 수 있다.
fuelGauge = fuel;
speed = 0;
}
void Car::show()
{
cout << "소유자 ID : " << gameID << endl;
cout << "연료 량 : " << fuelGauge << endl;
cout << "현재속도 : " << speed << endl;
}
void Car::accel()
{
if (fuelGauge <= 0)
return;
else
fuelGauge -= CAR::FUEL;
if (speed + CAR::ACC >= CAR::MAX)
{
speed = CAR::MAX;
return;
}
speed += CAR::ACC;
}
void Car::Break()
{
if (speed < CAR::BRK)
{
speed = 0;
return;
}
speed -= CAR::BRK;
}
int main()
{
Car run99; //클래스 객체 생성
run99.InitMembers("run99", 100);
run99.accel();
run99.accel();
run99.accel();
run99.show();
run99.Break();
run99.show();
return 0;
}
오류가 발생한다.
문제 03-2
- 문제 1
#include <iostream>
using namespace std;
class Calculator {
private:
int add;
int div;
int min;
int mul;
public:
void Init();
double Add(double x, double y);
double Div(double x, double y);
double Min(double x, double y);
double Mul(double x, double y);
void ShowOpCount();
};
void Calculator::Init()
{
add = 0;
div = 0;
min = 0;
mul = 0;
}
double Calculator::Add(double x, double y)
{
add++;
return x + y;
}
double Calculator::Div(double x, double y)
{
div++;
return x / y;
}
double Calculator::Min(double x, double y)
{
min++;
return x - y;
}
double Calculator::Mul(double x, double y)
{
mul++;
return x * y;
}
void Calculator::ShowOpCount()
{
cout << "덧셈 : " << add << " 뺄셈 : " << min << " 곱셈 : " << mul << " 나눗셈 : " << div << endl;
}
int main()
{
Calculator cal;
cal.Init(); // init함수는 Class안의 멤버변수들을 초기화해주는 함수로 가정
cout << "3.2 + 2.4 = " << cal.Add(3.2, 2.4) << endl;
cout << "3.5 / 1.7 = " << cal.Div(3.5, 1.7) << endl;
cout << "2.2 - 1.5 = " << cal.Min(2.2, 1.5) << endl;
cout << "4.9 / 1.2 = " << cal.Div(4.9, 1.2) << endl;
cal.ShowOpCount();
return 0;
}
- 문제2
#include <iostream>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
class Printer {
private:
char result;
public:
void SetString(char * str);
void ShowString();
};
void Printer::SetString(char * str)
{
strcpy(result, str);4
}
void Printer::ShowString()
{
cout << result << endl;
}
int main()
{
Printer pnt;
pnt.SetString("Hello World!");
pnt.ShowString();
pnt.SetString("I love C++");
pnt.ShowString();
return 0;
}
다음과 같이 작성하였으나 SetString에서 strcpy관련 에러와 char형 매개변수가 맞지 않다는 에러가 뜬다.
main함수 안에서 SetString 안에 넣어준 "Hello, World!"라는 문자열은 const char[13] 자료형이므로 매개변수도 const char str[100] 과 같은 형태로 바꾸어 준다.
그리고 strcpy 에러를 없애기 위해 #pragma warning(disable:4996)을 추가해준다.
#include <iostream>
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
class Printer {
private:
char result[100];
public:
void SetString(const char str[100]);
void ShowString();
};
void Printer::SetString(const char str[100])
{
strcpy(result, str);
}
void Printer::ShowString()
{
cout << result << endl;
}
int main()
{
Printer pnt;
pnt.SetString("Hello World!");
pnt.ShowString();
pnt.SetString("I love C++");
pnt.ShowString();
return 0;
}
객체와 객체간의 관계
#include <iostream>
using namespace std;
class FruitSeller
{
private:
int APPLE;
int NUM;
int MONEY;
public:
void InitMembers(int price, int num, int money)
{
APPLE = price;
NUM = num;
MONEY = money;
}
int SaleApples(int money)
{
int num = money / APPLE;
NUM -= num;
MONEY += money;
return num;
}
void ShowSalesResult()
{
cout << "남은 사과 : " << NUM << endl;
cout << "판매 수익 : " << MONEY << endl;
}
};
class FruitBuyer
{
int MONEY;
int APPLE;
public:
void InitMembers(int money)
{
MONEY = money;
APPLE = 0;
}
void BuyApple(FruitSeller& seller, int money)
{
APPLE += seller.SaleApples(money);
MONEY -= money;
}
void ShowBuyResult()
{
cout << "현재 잔액 : " << MONEY << endl;
cout << "사과 개수 : " << APPLE << endl;
}
};
int main()
{
FruitSeller seller;
seller.InitMembers(1000, 20, 0);
FruitBuyer buyer;
buyer.InitMembers(5000);
buyer.BuyApple(seller, 2000);
cout << "과일 판매자의 현황 " << endl;
seller.ShowSalesResult();
cout << "과일 구매자의 현황" << endl;
buyer.ShowBuyResult();
return 0;
}
'Langauge > C++' 카테고리의 다른 글
[열혈 C++ 프로그래밍] Chapter05(복사 생성자) 정리 및 문제 해결 (0) | 2021.02.16 |
---|---|
[열혈 C++ 프로그래밍] Chapter04(클래스의 완성) 정리 및 문제 해결 #2 (0) | 2021.02.14 |
[열혈 C++ 프로그래밍] Chapter04(클래스의 완성) 정리 및 문제 해결 #1 (0) | 2021.02.13 |
[열혈 C++ 프로그래밍] Chapter02 - C언어 기반의 C++ 2 (0) | 2021.02.10 |
C++ 벡터(vector) 사용법 정리 (0) | 2021.02.07 |