본문 바로가기

Programming/ C++

(C++)난 private고 넌 외부사람이야! 우린 안돼! 접근지정자에 대해 알아보자!

728x90
반응형


접근지정자란?

클래스 안의 멤버변수들의 접근범위를 지정하는 역할을 합니다.

접근지정자에는 3가지 종류가 있습니다. 만약 접근지정자를 지정해주지 않았을 때에는 default값으로 Private(개인, 비공개)로 지정됩니다.


접근지정자의 종류

1. public : public으로 접근지정자를 설정하게 된다면, 클래스 외부, 내부 모두 접근할 수 있습니다.


2. protected : class 내의 멤버들과 이 class를 상속받은 파생class의 멤버에게만 접근이 허용됩니다.


3. private : class 내의 멤버들만 접근할 수 있습니다.


==접근지정자의 사용방법==

class A

{

  . . .

}

class B : protected A // 그냥 A를 써주게 된다면 default값인 private로 지정.

{

 . . .

}

 이 뜻은 클래스 B가 클래스 A의 멤버들을 protected로 받겠다는 뜻입니다.



(코딩 예시)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
using namespace std;
 
class A
{
    int a1; //1
protected:
    int b1; //2
public:
    int c1; //3
    void setA1(int a1) { this->a1 = a1; }
    int getA1() { return a1; }
};
 
class B : protected A
{
    int a2; //4
protected:
    int b2; //5
public:
    int c2; //6
 
    void setA1(int a1) { A::setA1(a1); }
    int getA1() { return A::getA1(); }
    void setB1(int b1) { this->b1 = b1; }
    int getB1() { return b1; }
    void setA2(int a2) { this->a2 = a2; }
    int getA2() { return a2; }
    void setB2(int b2) { this->b2 = b2; }
    int getB2() { return b2; }
    void setC1(int c1) { this->c1 = c1; }
    int getC1() { return c1; }
    
    
};
cs


반응형