C++ Constructor

m._.jooong·2023년 4월 25일
0

C++

목록 보기
18/23

#include <iostream>

// 문자열 라이브러리
#include <string>
// C++ 표준 라이브러리
using namespace std;

//Fruit 라는 클래스 정의하기
class Fruit 
{
private:

    int m_Seed;
    int m_Count;
public:

    // :(콜론) 초기화 리스트로 초기화를 하는 과정이다
    Fruit() : m_Seed(2), m_Count(15)
    {
        cout << "생성자 호출" << endl;
        cout << "Seed : " << m_Seed << ", Count : " << m_Count << endl;
    }

    // 생성자 오버로딩이다
    // 초기화 리스트에서 앞은 멤버 변수로 인식하고, 뒷 부분은 매개 변수로 인식한다
    Fruit(int seed, int count = 0) : m_Seed(seed), m_Count(count)
    {
        cout << "Seed : " << m_Seed << ", Count : " << m_Count << endl;
    }

    ~Fruit()
    {
        cout << "소멸자 호출 " << endl;
    }
};

int main()
{
    /**
    객체의 생성과 소멸

    생성자 : 객체를 생성하면서 멤버 변수의 초기화 담당 
    소멸자 : 객체가 메모리에서 소멸될 때 할 일들을 지정해준다.
    */

    // Fruit 라는 클래스 정의하기

    // 동적 할당을 하게 되면 스마크 포인터를 쓰지 않는 이상 delete 연산자로 메모리에서
    // 객체 해제를 해 주어야 한다.
    Fruit* fruit = new Fruit();

    delete fruit;
    cout << endl;

}

0개의 댓글