C++

생성자와 소멸자

khon98 2020. 12. 15. 14:30

생성자

- C++에서는 생성자를 이용해 객체를 생성함과 동시에 멤버 변수를 초기화 활 수 있음

- 생성자는 특별한 메서드로 클래스의 이름과 동일한 이름의 메서드로 구현됨

- 생성자는 반환 값이 없음, 생성자는 여러 번 정의되어 다양한 방법으로 객체를 초기화할 수 있음

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Charactor {
private:
    string name;
    int ragePoint;
    int hp;
    int damage;
public:
    Charactor(string name, int hp, int damage) { // class와 동일한 이름으로 함수가 존재함
    this->name = name;
    this->ragePoint = 0;
    this->hp = hp;
    this->damage = damage;
    }
    void show() {
        cout << name << "[" << ragePoint << "]" << hp << " " << damage << '\n';
    }
};

int main(void) {
    Charactor charactor = Charactor("슬라임", 50, 10);
    charactor.show();
    system("pause");
    return 0;
}

 

기본 생성자

- C++에서 별도로 생성자를 구현하지 않으면 기본 생성자가 사용됨

- 기본 생성자는 매개 변수를 가지지 않으며 멤버 변수는 0, null 등의 값으로 초기화됨

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

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

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

 

복사 생성자

- 복사 생성자는 다른 인스턴스의 참조를 인수로 받아서 그 참조를 이용해 자신의 인스턴스를 초기화할 수 있도록 해줌

- 대표적인 복사 방법인 깊은 복사를 이용해 만들어진 인스턴스는 기존의 인스턴스와 다른 메모리 공간에 할당되어 독립적임

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Charactor {
private:
    string name;
    int ragePoint;
    int hp;
    int damage;
public:
    Charactor(string name, int hp, int damage) : name(name), ragePoint(0), hp(hp), damage(damage) {}
    Charactor(const Charactor& 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) {
    Charactor charactor1 ("슬라임", 10, 20);
    charactor1.pointUp();
    Charactor charactor2 (charactor1);
    charactor2.pointUp();
    charactor1.show();
    charactor2.show();
    system("pause");
    return 0;
}

 

소멸자

- 소멸자는 객체의 수명이 끝날을 때 객체를 제거하기 위한 목적으로 사용됨

- 객체의 수명이 끝날을 때 자동으로 컴파일러가 소멸자 함수를 호출

- 소멸자 또한 생성자처럼 클래스의 이름과 동일하며 물결 기호(~)를 이용해 정의할 수 있음

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Charactor {
private:
    string name;
    int ragePoint;
    int hp;
    int damage;
public:
    Charactor(string name, int hp, int damage) : name(name), ragePoint(0), hp(hp), damage(damage) {}
    ~Charactor() {
        cout << "[객체가 소멸.]\n";
    }
    void pointUp() { ragePoint++; }
    void show() {
        cout << name << "[" << ragePoint << "]" << hp << " " << damage << '\n';
    }
};

int main(void) {
    Charactor* charactor1 = new Charactor ("슬라임", 10, 20);
    charactor1->pointUp();
    Charactor charactor2 (*charactor1);
    charactor2.pointUp();
    charactor1->show();
    charactor2.show();
    
    delete charactor1; // 동적 할당을 이용하여 성공적으로 소멸
    delete &charactor2; // 동적 할당을 이용하지 않아 오류가 발생
    system("pause");
    return 0;
}

 

 

- 생성자와 소멸자는 객체를 초기화하거나 제거할 때 사용할 수 있는 문법