[C++] 클래스 Class

chxxrin·2024년 7월 24일
0

C++

목록 보기
14/22

접근제한자

  • public : 우리가 편하게 사용할 수 있는 클래스
  • private : 클래스 밖에서는 사용할 수 없음, 클래스 안의 멤버 함수에서만 사용할 수 있음, 프로그램 안정성을 위해서

Class

this pointer

  • 현재 만들고 있는 인스턴스의 주소
  • 여기서 this포인터는 my_class1의 주소이다

소멸자 : ~클래스명()

~MyClass() 
class MyClass
{
public: 
    MyClass()
    {
        // 호출 시점 확인
        cout << "MyClass()" << endl;
        cout << "this" << this << endl;
    }

    MyClass(int number)
    {
        cout << "MyClass(int number)" << endl;
        this->number_ = number;
        cout << "this" << this << endl;
    }

    ~MyClass() // ~ : 소멸자
    {
        // 호출 시점 확인
        cout << "~MyClass()" << endl;
    }

    void Increment(int a)
    {
        number_ += a;
    }

    void Print()
    {
        cout << number_ << endl;
    }

private: 
    int number_ = 0; // 초기값 
};

main 함수


int main()
{
    MyClass my_class1; // MyClass()
    MyClass my_class2(123); // 생성자 호출! MyClass(int number)

    cout << &my_class1 << endl; // this0x16d583224
    cout << &my_class2 << endl; // 0x16d583228

    my_class1.Print(); // 0
    my_class2.Print(); // 123

    my_class1.Increment(1); // 1 (0+1 = 1)
    my_class1.Print(); // ~MyClass()

    // 배열 사용 가능
    // 포인터 사용 가능(화살표 -> 사용)
    // 기본 자료형과 비교

    return 0;
}

전체 코드

/*
    홍정모 연구소 https://honglab.co.kr/
*/

#include <iostream>
#include <cstring>

using namespace std;

// public, private 접근 권한 확인

class MyClass
{
public: // 접근제한자(우리가 편하게 사용할 수 있음)
    MyClass()
    {
        // 호출 시점 확인
        cout << "MyClass()" << endl;
        cout << "this" << this << endl;
    }

    MyClass(int number)
    {
        cout << "MyClass(int number)" << endl;

        // this pointer
        // 현재 만들고 있는 인스턴스의 주소
        // this포인터는 my_class1의 주소이다
        this->number_ = number;
        cout << "this" << this << endl;
    }

    ~MyClass() // ~ : 소멸자
    {
        // 호출 시점 확인
        cout << "~MyClass()" << endl;
    }

    void Increment(int a)
    {
        number_ += a;
    }

    void Print()
    {
        cout << number_ << endl;
    }

private: // 접근제한자 (클래스 밖에서는 사용할 수 없음, 클래스 안의 멤버 함수에서만 사용할 수 있음, 프로그램 안정성을 위해서)
    int number_ = 0; // 초기값 
};

int main()
{
    MyClass my_class1; // MyClass()
    MyClass my_class2(123); // 생성자 호출! MyClass(int number)

    cout << &my_class1 << endl;
    cout << &my_class2 << endl;

    my_class1.Print(); // 0
    my_class2.Print(); // 123

    my_class1.Increment(1); // 1 (0+1 = 1)
    my_class1.Print(); // ~MyClass()

    // 배열 사용 가능
    // 포인터 사용 가능(화살표 -> 사용)
    // 기본 자료형과 비교

    return 0;
}

출처 : 홍정모 유튜브

0개의 댓글

관련 채용 정보