상세 컨텐츠

본문 제목

[c++]생성자와 소멸자

c++

by 래모 2021. 1. 20. 02:20

본문

생성자

: 객체가 생성될 때에 필드에게 초기값을 제공하고 필요한 초기화 절차를 실행하는 멤버 함수

  • 클래스의 이름과 동일
  • 초기화를 위한 데이터를 전달 받음
  • 반환값x
  • 반드시 public
  • 중복 정의o
#include <iostream>
using namespace std;

class Car {
private:
    int speed;
    int gear;
    string color;
public:
   Car() {
        speed = 0;
        gear = 1;
        color = "white"
   };
   Car(int s, int g, string c) {
        speed = s;
        gear = g;
        color = c;
   };
};

외부 정의도 가능

class Car {
private:
    int speed;
    int gear;
    string color;
public:
   Car();
   Car(int s, int g, string c);
};

Car::Car(){
    ...
}
Car::Car(int s, int g, string c) {
    ...
}

생성자를 정의하지 않는다면 컴파일러가 비어있는 디폴트 생성자를 자동으로 추가

 

소멸자

:객체가 소멸될 때 자동으로 발생하는 메서드

  • 클래스 이름에 ~가 붙음
  • 값 반환x
  • public멤버 함수로 선언
  • 소멸자는 매개 변수 받지 않음
  • 중복 정의 불가능
class Car {
private:
    int speed;
    int gear;
    string color;
public:
   Car() {
   		
        speed = 0;
        gear = 1;
        color = "white";
        cout << "생성자 호출" << endl;
   };
   ~Car() {
        cout << "소멸자 호출" << endl;
};

 

관련문제

백준 2535

www.acmicpc.net/problem/2535

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

[c++]클래스와 상속  (0) 2021.01.26
클래스의 기초  (0) 2021.01.20
배열과 포인터  (0) 2021.01.17

관련글 더보기