42Seoul/CPP Module 01

ex03

재윤 2023. 12. 1. 13:30
반응형
  • ex02에서 했던 레퍼런스와 포인터를 어디에서 쓸지 생각을 해보는 문제
#include "HumanA.hpp"
#include "HumanB.hpp"

int main()
{
	{
		Weapon club = Weapon("crude spiked club");
		HumanA bob("Bob", club);
		bob.attack();
		club.setType("some other type of club");
		bob.attack();
	}
	{
		Weapon club = Weapon("crude spiked club");
		HumanB jim("Jim");
		jim.setWeapon(club);
		jim.attack();
		club.setType("some other type of club");
		jim.attack();
	}
	return 0;
}

Weapon.hpp

#ifndef WEAPON_HPP
# define WEAPON_HPP

#include <iostream>

class Weapon{
	private:
		std::string type;
	public:
	Weapon(std::string type);
	~Weapon();
	const std::string &getType(void) const;
	void setType(const std::string type);
};

#endif

문제에서 HumanA는 항상 무기를 가지고 있다? → 레퍼런스 타입 왜? NULL값을 가질 수 없다.

HumanB는 무기를 안 가질 수도 있다? → 포인터 타입

HumanA.hpp

#ifndef HUMANA_HPP
# define HUMANA_HPP

#include <iostream>
#include "Weapon.hpp"

class HumanA{
	private:
	std::string name;
	Weapon &weapon;
	public:
		HumanA(std::string name, Weapon &weapon);
		~HumanA();
		void attack(void) const;
};

#endif

 

HumanB.hpp

#ifndef HUMANB_HPP
# define HUMANB_HPP

# include <iostream>
# include "Weapon.hpp"

class HumanB {
 private:
	std::string name;
	Weapon *weapon;
 public:
	HumanB(std::string name);
	~HumanB();
	void setWeapon(Weapon &weapon);
	void attack(void) const;
};

#endif
반응형

'42Seoul > CPP Module 01' 카테고리의 다른 글

ex05(함수 포인터 배열)  (0) 2023.12.02
ex04  (0) 2023.12.01
ex02  (0) 2023.12.01
ex01(객체 포인터 배열 할당)  (0) 2023.12.01
ex00  (0) 2023.12.01