C++/C++ 메모리

C++ 상속 부모, 자식 메모리

재윤 2024. 1. 24. 15:52
반응형

ScavTrap.hpp

#ifndef SCAVTRAP_HPP
# define SCAVTRAP_HPP

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

class ScavTrap : public ClapTrap
{
private:
	std::string name;
	unsigned int hitPoint;
	unsigned int energyPoint;
	unsigned int attackDamage;

public:
	ScavTrap();
	~ScavTrap();
	ScavTrap(std::string name);
	ScavTrap(const ScavTrap& scavTrap);
	ScavTrap& operator=(const ScavTrap& obj);

	void attack(const std::string& target);
	//std::string getName() const;
	void guardGate();
};

# endif

 

ClapTrap.hpp

#ifndef CLAPTRAP_HPP
# define CLAPTRAP_HPP

# include <iostream>

class ClapTrap{
protected:
	std::string name;
	unsigned int hitPoint;
	unsigned int energyPoint;
	unsigned int attackDamage;

public:
	ClapTrap();
	~ClapTrap();
	ClapTrap(std::string name);
	ClapTrap(const ClapTrap& ClapTrap);
	ClapTrap& operator=(const ClapTrap& obj);
	void attack(const std::string& target);
	void takeDamage(unsigned int amount);
	void beRepaired(unsigned int amount);

	virtual std::string getName() const;
	unsigned int getHitPoint() const;
	unsigned int getEnergyPoint() const;
	unsigned int getAttackDamage() const;
};

# endif
  • 현재 헤더들을 보면 변수가 같은 것을 볼 수가 있다 이것이 문제인데 한 번 이야기를 해보겠다.

클래스와 구조체가 거의 똑같다라고 보면 된다. 그래서 ClapTrap에서 생성된 변수들이 메모리에 적재되는데 ScavTrap은 상속을 받는다. 그러면 ClapTrap의 메모리를 그대로 복사해서 들고 가는데

거기 안에 똑같은 변수명인 자료형이 있으면 버그가 생길 수 있다 그래서 자식에서는 부모랑 다른 변수명을 해주는 것이 좋다.

반응형