Robotics/C++

C++ 접근 제어자 (Access Modifier) public / protected / private

Jeonggeun 2022. 12. 2. 22:53
728x90

 

public: 누구나 접근 가능

protected: 자식 클래스에서 접근 가능

private: 해당 클래스에서 접근 가능 (객체가 아니라 클래스임)

 

아래와 같이 "public:", "protected:", "private:" 밑에 변수를 선언하면 public, protected, private 멤버 변수 또는 멤버 함수가 됩니다. 

 

class ExampleClass
{
  public:
    int public_menber;
    void function_1()
    {
      std::cout << "this is public function" << std::endl;
    }
  
  protected:
    float protected_member;
    void function_2()
    {
      std::cout << "this is protected function" << std::endl;
    }
    
  private:
    double private_member;
    void function_3()
    {
      std::cout << "this is private function" << std::endl;
    }
};

 

만약 아래와 같이 표시를 하지 않는다면?

 

class ExampleClass
{
  int variable_1;
  int variable_2;
};

 

variable_1, variable_2 모두 private 멤버 변수가 됩니다.

반응형