C++의 중첩 클래스
이 기사에서는 C++에서 중첩 클래스와 구조가 어떻게 작동하는지 설명합니다.
C++의 다른 클래스 내부에 class 또는 struct 객체 정의
때때로 우리 클래스는 일반적으로 사용자 정의 struct 또는 class 객체로 정의되는 소위 도우미 데이터 유형이 필요합니다. 이러한 도우미 클래스는 다른 클래스 내에서 정의할 수 있으며 이러한 경우 중첩 유형 또는 중첩 클래스라고 합니다. 후자의 개념은 좋은 범위 경계 및 액세스 제어와 같은 프로그래머에게 많은 이점을 제공합니다.
다음 예제는 중첩 클래스를 정의할 수 있는 간단한 시나리오를 보여줍니다. 메인 클래스인 CircularList는 순환 연결 목록을 구현하며 ListNode라는 복합 유형인 노드를 정의해야 합니다. 이 경우 후자는 struct 키워드를 사용하여 전역 범위에서 정의됩니다. 따라서 해당 멤버는 다른 클래스에서 공개적으로 액세스할 수 있습니다.
#include <iostream>
#include <string>
using std::string;
struct ListNode {
struct ListNode *next = nullptr;
string data;
} typedef ListNode;
class CircularList {
public:
explicit CircularList(string data) {
head = new ListNode;
head->next = head;
head->data = std::move(data);
end = head;
};
ListNode *insertNodeEnd(string data);
ListNode *insertNodeHead(string data);
void printNodes();
~CircularList();
private:
ListNode *head = nullptr;
ListNode *end = nullptr;
};
int main() { return EXIT_SUCCESS; }
또는 ListNode 정의를 CircularList 클래스로 이동할 수 있습니다. ListNode는 전역 네임스페이스에서 액세스할 수 없으므로 중첩된 클래스 이름 앞에 CircularList:: 네임스페이스를 포함해야 합니다. 또한 일반적인 액세스 제어 규칙도 중첩 클래스에 적용되기 때문에 중첩 클래스에 어떤 액세스 지정자가 있는지도 중요합니다.
이 경우 ListNode는 public 멤버 클래스로 정의되어 있으므로 CircularList::ListNode 표기법을 사용하여 main 함수에서 액세스할 수 있습니다. 중첩된 클래스가 protected 멤버로 정의된 경우 클래스, 후자의 friend 클래스 및 파생 클래스를 둘러싸서 액세스할 수 있습니다. 반면에 중첩 클래스에 대한 private 지정자는 해당 클래스와 friend 클래스 내에서만 액세스할 수 있음을 의미합니다.
#include <iostream>
#include <string>
using std::string;
class CircularList {
public:
// Helper Types ->
struct ListNode {
struct ListNode *next = nullptr;
string data;
} typedef ListNode;
// Member Functions ->
explicit CircularList(string data) {
head = new ListNode;
head->next = head;
head->data = std::move(data);
end = head;
};
ListNode *insertNodeEnd(string data);
ListNode *insertNodeHead(string data);
void printNodes();
~CircularList();
private:
ListNode *head = nullptr;
ListNode *end = nullptr;
};
int main() {
// ListNode *n1; // Error
CircularList::ListNode *n2;
return EXIT_SUCCESS;
}
일반적으로 중첩 클래스는 해당 멤버에 대한 일반적인 액세스 지정자를 가질 수 있으며 규칙은 바깥쪽 클래스에 일반으로 적용됩니다. 한편, 중첩 클래스는 둘러싸는 클래스의 멤버에 대한 특별한 액세스 권한이 부여되지 않습니다.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook