11. 생성자 초기화 리스트(initializer list)가 궁금해.

2021. 11. 25. 18:31c++/기초

우리는 초기화를 할 때 생성자의 body 안에다가 값을 대입한다.

하지만 다른 방법도 있다!

class Human {
private:
	char* name;
	int age;
	int power;
	int intelligence;
	int hp;
	int recent_x, recent_y;
public:
	Human(const char* a, int age_, int power_, int intelligence);
    }
    
Human::Human(const char* a, int age_, int power_, int intelligence_) :
	age(age_), power(power_), intelligence(intelligence_) {
	hp = 100;
	name = new char[strlen(a)+1];
	strcpy(name, a);

위는 생성자 list를 이용한 초기화 방식이다.

 

위 방식을 이용하면 

실제로는 age = age_ 의 형태로 이루어진다.

hp처럼 값을 하드코딩 방식으로 할당해주게 된다면,

int hp; hp = 100 의 형태로 이루어진다.

 

사실 별 차이 없어 보인다.ㅎㅎ

 

하지만 상수(const)와 레퍼런스(&,reference)는 생성과 초기화가 이루어져야 하기 때문에 멤버 변수에 상수나 레퍼런스가 있다면 꼭 초기화 리스트 방식으로 이루어져야 한다!

 

class Human {
private:
	char* name;
	int age;
	int power;
	int intelligence;
    const int luck;
	int hp;
	int recent_x, recent_y;
public:
	Human(const char* a, int age_, int power_, int intelligence);
    }
    
Human::Human(const char* a, int age_, int power_, int intelligence_) :
	age(age_), power(power_), intelligence(intelligence_), luck(0) {
	hp = 100;
	name = new char[strlen(a)+1];
	strcpy(name, a);

상수 luck은 위처럼 해주어야함.ㅎㅎ

반응형