언어/C++

[C++] Inner Class (중첩 클래스, Nested Class)

겜도리도리 2022. 1. 6. 15:17
반응형

특정 클래스 내부에서만 사용될 클래스를 중첩 클래스라고 한다.

 

내부에 선언된 클래스는 해당 클래스에서만 사용할 수 있고, 외부에서는 사용하지 못한다.

(public으로 선언한 경우에는 접근자체는 가능하다.)

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
#include<iostream>
#include<string>
using namespace std;
 
class Person
{
public:
    string name;
 
    class Address
    {
    public:
        string country;
        string city;
        int houseNumber;
    };
 
    Address add;
 
    void print()
    {
        cout << "Country : " << add.country << endl;
        cout << "City : " << add.city << endl;
        cout << "HouseNumber : " << add.houseNumber << endl;
    }
};
int main()
{
    Person Kunwo;
    Address addr; // 컴파일 에러
    Person::Address ExampleAdd;
 
    Kunwo.add.country = "Korea";
    Kunwo.add.city = "Seoul";
    Kunwo.add.houseNumber = 5;
 
    Kunwo.print();
    return 0;
}
cs

Person 내부에서만 사용될 Address를 선언하고 main에서 Person 클래스를 만들어주는 예제이다.

Address 클래스를 외부에서 만드려고 하면 컴파일 에러가 발생한다.

 

InnerClass의 접근지정자가 public인 경우에는 외부 클래스를 통해 접근 가능하다.

Address 클래스의 접근지정자가 public이므로 Person::Addreess를 통해 Address 클래스를 만들어 줄 수 있다.

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
#include<iostream>
#include<string>
using namespace std;
 
class LinkedList
{
private:
    struct Node
    {
        int data;
        Node* prev, * next;
    };
 
    Node* head, * tail;
 
public:
    LinkedList();
    ~LinkedList();
    void Insert(Node* p, int a);
    void Delete(Node* p);
    int GetData(Node* p);
};
int main()
{
    return 0;
}
cs

위의 코드는 이중 연결 리스트의 예시인데, LinkedList 클래스 안의 Node는 외부에서 사용할 필요가 전혀 없다.

따라서 private 클래스로 선언한 뒤, 내부에서만 사용하게끔 할 수 있다.

 

더보기

https://c-annotationskr.sourceforge.io/cplusplus17.html

반응형

'언어 > C++' 카테고리의 다른 글

[C++] Upper_bound, Lower_bound  (0) 2022.02.13
[C++ STL] map  (0) 2022.01.21
[C++] Iterator  (0) 2021.12.30
[C++] #pragma once와 #ifndef ~ #endif  (0) 2021.12.26
[C++] shared_ptr 직접 구현해보기  (0) 2021.12.16