SW개발/C++

C++ 접근 지정자 (Access Specifier)

Caniro 2021. 3. 12. 17:47
반응형

접근 지정자 (Access Specifier)

  • 종류

    • public : 어디서든 접근 가능하다.

    • private : 해당 클래스와 friend 클래스만 접근 가능하다.

    • protected : private 특성을 기본으로, 상속받은 자식 클래스도 접근 가능하다.

  • 명시하지 않는 경우, 기본 값은 private이다.

  • private이어도 같은 클래스면 다른 인스턴스의 멤버를 사용할 수 있다.

    class Date
    {
      int    year_;
      int    month_;
      int    day_;
    
      void copyFrom(const Date& original)
      {
        year_ = original.year_;
        month_ = original.month_;
        day_ = original.day_;
      }
    };
  • public 멤버 변수들에 대해 uniform initialization이 가능하다.

    #include <iostream>
    
    class Date
    {
    public:
        int    year_;
        int    month_;
        int    day_;
    };
    
    int        main()
    {
        using namespace std;
    
        Date a{ 2021, 3, 1 };
        cout << a.year_ << ' ' << a.month_ << ' ' << a.day_ << '\n';
    }
    
    /* stdout stderr
    2021 3 1
    */
반응형