본문 바로가기

C

c++ 상속 public, protected, private 완벽 정리 코드

public, protected, private 클래스 상속에 대한 완벽 정리를 기록용으로 코드로 적어 놓았다.

 

코드 >>

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
 
class Animal
{
public:
    void sleep() const
    {
        std::cout << "I'm sleeping" << std::endl;
    }
};
class Human : public Animal
{
public:
    void driveCar() const
    {
        std::cout << "I'm driving" << std::endl;
    }
};
 
class Base
{
protected:
    int pro;
private:
    int pri;
public:
    
    void setPRI(int n)
    {
        pri = n;
    }
    void setPRO(int n)
    {
        pro = n;
    }
};
 
class Derived_public : public Base
{
public:
    void test()
    {
        Base::pro = 100// 접근 가능(protected)
        //Base::pri = 0; // 접근 불가(private)
    }
};
 
class Derived_protected : protected Base
    // Derived가 보기에 Base의 public이 protected처럼 보임
    // 즉 setPRI, setPRO는 접근 불가
{
public:
    void test()
    {
        Base::pro = 100;
        //Base::pri = 0; // 접근 불가(private)
    }
};
 
class Derived_private : private Base
    // Derived가 보기에 Base의 public이 protected처럼 보임
    // 즉 setPRI, setPRO는 접근 불가
{
public:
    void test()
    {
        Base::pro = 100;
        //Base::pri = 0; // 접근 불가(private)
        //std::cout << "잘 실행 되었습니다..." << std::endl;
    }
};
 
 
int main()
{
    Human woonggon;
    woonggon.driveCar();
    woonggon.sleep();
    
    Base base;
    base.setPRI(10);
    base.setPRO(100);
    //base.pro = 0;        // 불가(protected)
    //base.pri = 0;        // 불가(private)
 
    Derived_public derived_public;
    derived_public.setPRI(10);
    derived_public.setPRO(100);
 
 
    Derived_protected derived_protected;
    //derived_protected.setPRI(10); // 불가(protected로 상속하면 public이 protected처럼 됨)
    //derived_protected.setPRO(100); // 불가(protected로 상속하면 public이 protected처럼 됨)
    
    Derived_private derived_private;
    //derived_private.setPRI(10); // 불가(private로 상속하면 public이 private처럼 됨)
    //derived_private.setPRO(100); // 불가(private로 상속하면 public이 private처럼 됨)
    derived_private.test();
    return 0;
}