[C++] 31. 구조체 선언부와 구현부의 분리

2022. 6. 16. 17:04코딩 1막 <C++개념편>

728x90

1. <상호 참조를 할만한 두 구조체를 만들고 선언부와 구현부를 분리해보자>

구조체로 몬스터와 플레이어를 생성하였고, 각 구조체마다 기능과 속성을 부여하였다.

그 다음 선언부와 구현부를 분리하여 형태를 갖추었다.

함수의 구현부를 작성할때 다음과 같은 연산자를 꼭 추가해주어 어떤 구조체의 함수인지를 표기해야한다

// 함수가 어느 구조체에 있는지 알려주기 위해 :: 연산자 사용
// [문법] 리턴타입 해당구조체::해당함수()
#include <iostream>
#include <string>

using namespace std;

// 선언부와 구현부의 분리
// 구조체의 선언부 : 구조체가 존재한다
struct Monster;
struct Player;

// 구조체의 정의부
struct Monster
{
	int hp;
	int atk;

	// 함수의 선언부
	void ShowHp();
	void Attack(Player* player);
	void Hit(float damage);
};

// 구조체의 정의부
struct Player
{
	int hp;
	int atk;

	// 함수의 선언부
	void ShowHp();
	void Attack(Monster* monster);
	void Hit(float damage);
};

void main()
{
	Monster monsterA;
	monsterA.hp = 100;
	monsterA.atk = 10;

	Player player;
	player.hp = 100;
	player.atk = 20;

	while (player.hp > 0 && monsterA.hp > 0)
	{
		player.Attack(&monsterA);
		monsterA.ShowHp();

		monsterA.Attack(&player);
		player.ShowHp();
	}
}

// Monster 함수 구현부
void Monster::ShowHp()
{
	cout << " 몬스터의 체력 : " << hp << endl;
}

void Monster::Attack(Player* player)
{
	player->Hit(atk);
}

void Monster::Hit(float damage)
{
	hp -= damage;
}


// Player 함수 구현부
void Player::ShowHp()
{
	cout << " 플레이어의 체력 : " << hp << endl;
}

void Player::Attack(Monster* monster)
{
	monster->Hit(atk);
}

void Player::Hit(float damage)
{
	hp -= damage;
}

출력 결과

2. <간단한 구조체 하나를 만들고 선언부와 구현부를 분리해보자>

#include <iostream>
#include <string>

using namespace std;

// 구조체 선언부
struct Temp;

// 구조체 정의부
struct Temp
{
	int value;

	// Temp 함수 선언부
	Temp();
	Temp(int _value);
	void ShowValue();
};

// Temp 함수 구현부
// 함수가 어느 구조체에 있는지 알려주기 위해 :: 연산자 사용
// [문법] 리턴타입 해당구조체::해당함수()
Temp::Temp()
{

}

Temp::Temp(int _value)
{
	value = _value;
}

void Temp::ShowValue()
{
	cout << "Temp의 value값 : " << value << endl;
}

void main()
{
	Temp temp;
	temp = 10;
	temp.ShowValue();
}

출력 결과

* 선언부와 구현부를 분리하는 순서는 다음 사진을 통해 설명으니 참고하기 바란다.

728x90

'코딩 1막 <C++개념편>' 카테고리의 다른 글

[C++] 33. 클래스  (0) 2022.06.22
[C++] 32. 콘솔 글자색 바꾸기  (0) 2022.06.16
[C++] 30. 벡터(vector)란 무엇인가?  (0) 2022.06.14
[C++] 29. 문자열: string이란?  (0) 2022.06.14
[C++] 28. 가상함수  (0) 2022.06.10