컴퓨터 언어/C++

[C++] C++ 9일차 상속 1

훈츠 2020. 4. 9. 10:41
반응형

안녕하세요. 훈츠입니다. 금일은 상속에 대해 정리 해보도록 하겠습니다. 


상속 (inheritance)

기본 클래스의 속성을 물려 받는것을 상속이라고 합니다.  상속을 받는 클래스를 자식 클래스라고 부르며, 상속을 해주는 클래스를 부모 클래스라고 부릅니다. 자식 클래스에서는 부모 클래스의 속성을 그대로 사용할수도 있고, 새로운 기능을 추가 할수도 있습니다. 

  • 상속을 해주는 클래스 : base class, super class, parent class , 최상위 클래스 라고 불립니다. 
  • 상속을 받는 클래스 : sub class, child class, 자식 클래스, 하위클래스, 최화위 클래스 라고 불립니다. 

※ 형식1 (단일 상속)

1
2
3
4
5
6
7
8
9
10
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class Derived : [접근지정자] Base class // 상속 할때는 ':' 키워드 사용 합니다. 
{
    //member list 
}
 
class A {  } ; //Base Class
class B : public A { } ; //Sub Class 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

※ 형식2 (다중 상속)

1
2
3
4
5
6
7
8
9
10
11
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class Derived : [접근지정자] Base class , [접근 지정자] Base2 class
{
    //member list 
}
 
class A {  } ; //A Base Class
class B {  } ; //B Base Class
class C : public A, protected B { } ; //Sub Class C 두개이 클래스를 상속 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

※ 예시 

  • class A 에서 접근 제어자가 상속 받은 class B 안에서 그대로 적용되면서, private 를 제외하고 접근이 허용됩니다. 
  • class B : 접근제어자 A = 이곳에서 접근제어자는 main() 함수에서 객체를 만들고 그곳에서 접근 할때 적용되어집니다. 
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
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
#include <iostream>
#include <fstream>
using namespace std;
 
class A
{
private : 
    int n_pri=2;
    void Print2() {
        cout << "n_pri" << n_pri << endl;                    
    }
public
    int n_pub=1;
    void Print() {
        cout << "n_pub" << n_pub << endl;
        cout << "n_pro" << n_pro << endl;
        cout << "n_pri" << n_pri << endl;
    }
protected:
    int n_pro = 3;
    void Print3() {
        cout << "n_pro" << n_pro << endl;
    }
};
class B : public A
{
public :
    void show() {
        cout << this->n_pro << endl;
    }
};
int main()
{
    A a;
    a.Print();
    
    B b;
    b.Print();
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs
 
반응형