'생성자'에 해당되는 글 2건

  1. 2020.12.15 생성자와 소멸자
  2. 2020.06.16 생성자(constructor)

생성자와 소멸자

C++ 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;
}

 

 

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

'C++' 카테고리의 다른 글

캡슐화 기법  (0) 2020.12.15
오버로딩  (0) 2020.12.15
클래스 상속  (0) 2020.12.15
C++의 클래스  (0) 2020.12.14
C언와 C++ 비교  (0) 2020.12.14
Posted by khon98
,

생성자(constructor)

자바 2020. 6. 16. 21:45

생성자

- 생성자는 java 클래스에서 객체를 생성할 때 자동으로 호출되는 메서드를 의미한다

 

- 생성자는 return type이 없으며 메서드의 이름은 클래스의 이름과 동일하다

 

- 생성자는 객체를 생성할 때 반드시 수행되어야 하는 코드가 있거나 초기화의 작업을 하는 데 사용되어진다

 

사용 양식

- public 클래스명(매개변수) {

코드

}

 

생성자의 Overloading

default 생성자

- 생성자를 클래스에 만들지 않으면 매개 변수가 없는 생성자가 자동으로 만들어지며 내부에는 소스 코드가 없다

 

- 이렇게 매개 변수가 없는 생성자를 default 생성자라고 부른다

 

- 생성자를 개발자가 직접 만들 경우 default 생성자는 자동으로 생성되지 않는다

 

매개 변수가 있는 생성자

- 생성자는 매개 변수를 가질 수 있으며 매개 변수가 있는 생성자를 만들 경우 default 생성자가 생성되지 않는다

 

- 매개 변수의 형태를 다르게 하여 여러 개의 생성자를 생성할 수 있으며 객체를 생성할 때 선택할 수 있다

 

--------------------------------------------------------------------------------------------------------------------

newConstructorTest( );

newConstructorTest(10);

newConstructorTest(100, 200);

}

// 매개 변수가 없는 생성자 - default 생성자

public ConstructorTest( ){

     System.out.println("Default 생성자");

}

// 매개 변수가 있는 생성자

public ConstructorTest(int a) {

     System.out.println("넘겨 받은 정수 값 : " + a);

}

public ConstructorTest(int a, int b) {

     System.out.println("두 수의 합 : " + (a + b));

}

--------------------------------------------------------------------------------------------------------------------

 

1. 객체를 생성할 때 자동으로 호출되는 메서드를 생성자라고 한다

 

2. 매개 변수가 없는 생성자를 default 생성자라고 부르며 클래스를 만들 때 생성자를 만들지 않으면 default 생성자가 자동으로 추가된다

 

3. 생성자의 매개 변수를 다르게 하여 여러 개의 생성자를 만들 수 있으며 객체를 생성할 때 선택할 수 있다

 

4. 생성자는 프로그램을 개발할 때 class를 설계하고 이 클래스로부터 객체가 생성이 될 때 어떠한 특정 소스 코드가 자동으로 이루어져야 하는 경우 생성자를 만들어 사용한다

'자바' 카테고리의 다른 글

다형성(Polumorphism)  (0) 2020.06.20
상속(inheritance)  (0) 2020.06.17
args  (0) 2020.06.16
배열(Array)  (0) 2020.06.06
Package  (0) 2020.06.03
Posted by khon98
,