본문 바로가기

[C,C++]

[C,C++ 개념정리] encapsulation, access specifiers & functions

728x90

 < encapsulation, access specifiers & functions >

 

class 멤버변수에 대한 default - access specifier는 private이다. 인스턴스의 멤버변수에 대한 접근을 유의해서 보자. 당연한 얘기지만, 같은 클래스 내의 함수가, 동일한 클래스 내의 변수로의 접근은 접근지정자와 관계없이 접근이 가능하다. encapsulation의 철학이다.  

- 코드 - 

/*
    <2020.04.05>

    [8.2강 캡슐화(encapsulation), 접근지정자(access specifiers), 접근함수(access functions)]

    최근에는 연관관계를 잘 이해하고, 이를 깔끔하게 유지하는 사람들을 두고 프로그래밍을 잘한다고 한다.
    encapsulation에서는 내부 변수값들을 default인 private으로 선언하고, public 함수로 접근하게 만든다.
    const int& 의 의미
    - 참조는 항상 초기화해야 한다.
    - 값을 전달 -> 복사본을 전달하게 됨
    - 변경하지 말아야 할 클래스/함수 외부값을 함부로 변경하지 못하게 하므로써 프로그램의 정확성/
      보안이 늘어나는 효과이 있다.

*/

#include <iostream>
#include <string>
#include <vector>

using namespace std;

// struct Date
// {
//     int m_month;
//     int m_day;
//     int m_year;
// };

class Date //구조체와 똑같아 보이지만, 그대로 struct->class로 변경하면 main함수에서 접근이 불가하다.
{
// public:     // access specifier -> private : default값, 외부에서 접근 차단
                              //-> public : 해당 클래스 외부에서 접근 허용
                              //-> protected
    int m_month;
    int m_day;
    int m_year;

public: // 같은 클래스의 경우에는 함수에서 private 개체들에게 접근이 가능하다.
    void setDate(const int& month_input, const int& day_input, const int& year_input){
        m_month = month_input;
        m_day = day_input;
        m_year = year_input;
    }

    void setMonth(const int& month_input){
        m_month = month_input;
    }

    const int& getDay(){
        return m_day;
    }

    void copyFrom(const Date& original){ // Date의 인스턴스이므로 아래와 같은 접근이 가능하게 된다.
        m_month = original.m_month;
        m_day = original.m_day;
        m_year = original.m_year;
    }
};



int main()
{
    Date today; // {8, 4, 2025 }; -> 생성자를 사용하는 방법도 있음
    // today.m_month = 8; // 이런 경우에 class access specifier가 설정되어있지 않다면 접근할때 에러가 난다.
    // today.m_day = 4;
    // today.m_year = 2025;
    today.setDate(8,4,2025);
    today.setMonth(10);
    cout << today.getDay() << endl;

    Date copy;
    //copy.setDate(today.getMonth(), today. ... ) -> 복사하고자 하는데 이런식으로 하면 굉장히 귀찮아 진다.
    copy.copyFrom(today); // -> 이런식으로 처라할 수도 있다. why? 어짜피 같은 클래스에서 선언된 함수이니까!!
    cout << copy.getDay() << endl;

    return 0;
}

 

 - 출력 결과 -

728x90