C++ #03 생성자와 소멸자

underlier12·2020년 2월 1일
0

C++

목록 보기
3/19

03. 생성자와 소멸자

생성자

C++에서 생성자(Constructor)를 이용해 객체를 생성함과 동시에 멤버 변수를 초기화 할 수 있다. 생성자는 특별한 메소드로 클래스 이름과 동일한 이름으로 구현된다.

생성자의 특징

  1. 생성자는 반환값이 없음
  2. 생성자는 여러번 정의 될 수 있음(매개변수 다양화)
#include <iostream>
#include <string>

using namespace std;

class Character {
private: 
	string name;
	int ragePoint;
	int hp;
	int damage;
public:
	Character(string name, int hp, int damage) {
		this->name = name;
		this->ragePoint = 0;
		this->hp = hp;
		this->damage = damage;
	}
	void show() {
		cout << name << "[" << ragePoint << "] " << hp << " " << damage << "\n";
	}
};

int main(void) {
	Character slime = Character("Slime", 50, 10);
	slime.show();
	system("pause");
	return 0;
}

기본 생성자

C++에서 별도로 생성자를 구현하지 않으면 기본 생성자(Default Constructor)가 사용된다. 기본 생성자는 매개 변수를 가지지 않으며 멤버 변수는 0, NULL 등으로 초기화 된다.

#include <iostream>
#include <string>

using namespace std;

class Character {
private: 
	string name;
	int ragePoint;
	int hp;
	int damage;
public:
	void show() {
		cout << name << "[" << ragePoint << "] " << hp << " " << damage << "\n";
	}
};

int main(void) {
	Character slime = Character();
	slime.show();
	system("pause");
	return 0;
}

복사 생성자

복사 생성자(Copy Constructor)는 다른 인스턴스의 참조(Reference)를 인수로 받아 그 참조를 이용해 자신의 인스턴스를 초기화 할 수 있도록 해준다. 대표적인 복사 방법인 깊은 복사(Deep Copy)를 이용해 만들어진 인스턴스는 기존의 인스턴스와 다른 메모리 공간에 할당되어 독립적이다.

#include <iostream>
#include <string>

using namespace std;

class Character {
private: 
	string name;
	int ragePoint;
	int hp;
	int damage;
public:
	// this 키워드 사용하지 않고 축약하여 작성
	Character(string name, int hp, int damage) : name(name), ragePoint(0), hp(hp), damage(damage) {}
	// 복사 생성자
	Character(const Character& other) {
		name = other.name;
		ragePoint = other.ragePoint;
		hp = other.hp;
		damage = other.damage;
	}
	void pointUp() { ragePoint++; }
	void show() {
		cout << name << "[" << ragePoint << "] " << hp << " " << damage << "\n";
	}
};

int main(void) {
	Character slime1("슬라임", 10, 20);
	slime1.pointUp();
	Character slime2(slime1);
	slime2.pointUp();
	slime1.show();
	slime2.show();
	system("pause");
	return 0;
}

소멸자

소멸자(Destructor)는 객체의 수명이 끝났을 때 객체를 제거하기 위한 목적으로 사용된다. 객체의 수명이 끝났을 때 자동으로 컴파일러가 소멸자 함수를 호출한다. 클래스명과 동일하며 '~'기호를 사용한다.

#include <iostream>
#include <string>

using namespace std;

class Character {
private: 
	string name;
	int ragePoint;
	int hp;
	int damage;
public:
	// this 키워드 사용하지 않고 축약하여 작성
	Character(string name, int hp, int damage) : name(name), ragePoint(0), hp(hp), damage(damage) {}
	// 소멸자
	~Character(){
		cout << "[객체가 소멸됩니다.]\n";
	}
	void pointUp() { ragePoint++; }
	void show() {
		cout << name << "[" << ragePoint << "] " << hp << " " << damage << "\n";
	}
};

int main(void) {
	Character* slime1 = new Character("슬라임", 10, 20);
	slime1->pointUp();
	Character slime2(*slime1);
	slime2.pointUp();
	slime1->show();
	slime2.show();

	delete slime1; // 동적 할당을 이용했으므로 소멸 됨
	//delete& slime2; // 동적 할당하지 않았으므로 오류 발생
	system("pause");
	return 0;
}
profile
logos and alogos

0개의 댓글