#include <iostream>
#include<iomanip>
using namespace std;
//초기화 리스트
//멤버 변수 초기화 ? 다양한 문법이 존재
//초기화를 하지 않고 사용할 경우 쓰레기값을 사용하게 된다!
//-버그 예방
//-포인터 등 주소값이 연루되어 있을 경우
//초기화 방법
//-생성자 내에서 초기화
//-초기화리스트
//-C++11 문법
//초기화 리스트
//-일단 상속 관계에서 원하는 부모 생성자 호출할 때 필요하다.
//-생성자 내에서 초기화 vs 초기화 리스트
//--일반 변수는 별 차이 없음
//--멤버 타입이 클래스인 경우 차이가 난다
//--정의함과 동시에 초기화가 필요한 경우 (참조타임, const 타입)
class Inventory {
public:
Inventory() { cout << "Inventory()" << endl; }
Inventory(int size) { cout << "Inventory(int size)" << endl; }
~Inventory() { cout << "~Inventory()" << endl; }
};
class Player {
public:
Player() { }
Player(int id) { }
};
//Is-A 관계 (Knight Is-A Player? 기사는 플레이어다) OK-> 상속관계
//Has-A 관계 (Knight Has-A Inventory? 기사는 인벤토리를 포함하는가?) OK-> 포함관계
class Knight : public Player {
public:
//생성자와 초기화리스트를 사용한 방법
//Const나 Ref같이 선언과 초기화가 동시에 필요한 변수들은 초기화 리스트를 사용
Knight():Player(1),_hp(100),_inventory(20),_hpRef(_hp),_hpConst(100) {
/*
선처리 영역
Player(int id) 생성자 호출
Inventory() 생성자 호출
*/
_hp = 200;
//_inventory = Inventory(20); //이 방법으로 초기화할 경우 선처리영역에서 한번 이 코드에서 한번 총 두번의 생성자 호출이 이뤄짐
}
public:
int _hp;
Inventory _inventory; //포함관계
//C++11 방식의 초기화로 하면 편하긴 하다
//다만 보수적인 팀은 모던 C++을 사용하지 않을 수도 있으므로 주의!
int& _hpRef=_hp;
const int _hpConst=100;
};
int main()
{
Knight k;
cout << k._hp << endl;
return 0;
}