C언어 C++ Programming

[C++언어]Class의 Protected 수정, 출력하여 사용하는 법 (예제 포함)

끄적끄적아무거나 2022. 1. 4. 17:34
반응형

 

목차

     

     

     

     

     

     

    [C++언어]Class의 Protected 수정, 출력하여 사용하는 법

     

    앞서 포스트에서 상속(Inheritance)에 대해 알아 보았습니다.

    https://scribblinganything.tistory.com/435

     

    [C++언어] 상속이란? 예제로 살펴보기(Inheritance)

    목차 [C++언어] 상속이란? 상속이란 부모 클래스(Base Class)와 자식 클래스(Derived Class) 두개의 클래스가 있을 때 자식 클래스에서 부모 클래스의 method 나 attribute를 물려 받아서 동일하게 가지는 것

    scribblinganything.tistory.com

     

    이번에는 상속을 사용해서  Protected로 보호되고 있는 값을 불러오거나 수정하는 방법에 대해 알아 보겠습니다.

     

    protected 를 사용하면 해당 클래스 내에서만 Protected 된 인자나 Method에 접근할 수 있지만 상속을 사용하면 Protected된 인자나 Method를 사용할 수 있습니다.

     

    • 상속으로 연결된 자식 클래스는 부모 클래스의 Protected 된 값에 접근이 가능 하다.

     

     

    [C++언어]Class의 Protected 수정, 출력  예제

     

    예제 코드>>

    #include <iostream>
    using namespace std;
    
    class Years {
    protected:
        int this_year = 2021;
    };
    
    class Korea : public Years {
    public:
        void set_this_year(int year) {
            this_year = year;
        }
        int return_this_year() {
            return this_year;
        }
    };
    
    int main() {
        Korea korea_y;
        cout << "Korea's last year is " << korea_y.return_this_year() << "\n";
        korea_y.set_this_year(2022);
        cout << "Korea's this year is " << korea_y.return_this_year() << "\n";
        return 0;
    }

     

    4~7번 라인 : 부모 클래스

    5번 라인 : Protected로 this_year 인자에 대한 접근을 Years 클래스로 제한하였다.

    9~17번 라인 : 자식 클래스

    9번 라인 : Years 클래스를 Korea 클래스가 상속하였다. 

    11~13번 라인 : set_this_year 함수는 public으로 외부에서 접근 가능하다.

    12번 라인 : 상속을 이용해서 this_year에 접근 가능 하다.

     

     

    결과>>

    Korea's last year is 2021
    Korea's this year is 2022

     

     

     

    반응형