중첩된 형식 이름
Microsoft C++에서는 이름이 있는 중첩 형식과 익명 중첩 형식을 둘 다 선언할 수 있습니다. 익명 구조체 및 클래스는 C++에 대한 Microsoft 특정 확장입니다. 익명 공용 구조체가 표준입니다.
[::] class-name :: class-name
[::] template-id :: class-name
[::] class-name :: template-id
[::] template-id :: template template-id
:: template template-id :: template template-id
설명
위의 첫 번째 class-name은 바깥쪽 클래스를 참조하고 두 번째 class-name은 안쪽 클래스를 참조합니다. 이 이름은 더 중첩될 수 있습니다. 그러므로
Outer::Inner
::Outer::Inner
::Outer::Inner::Inner2
클래스의 모든 유효한 이름입니다. 클래스 이름 대신 다음과 같이 선택적 template 키워드와 함께 템플릿 식별자를 사용할 수 있습니다.
MyClass<int>::Inner
Outer<int>::template Inner<int>
프로그래밍 상황에서는 중첩 형식을 정의하는 것이 좋습니다. 이 형식은 정의된 클래스 형식의 멤버 함수에만 표시됩니다. 범위 결정 연산자(::)를 사용해 정규화된 형식 이름을 생성하여 이 형식을 표시할 수도 있습니다.
참고
중첩 형식이 적용되며 자주 사용되는 클래스 계층 구조 중 하나가 iostream입니다.iostream 헤더 파일에서 ios 클래스의 정의에 iostream 라이브러리 전용으로 패키지되는 일련의 열거 형식이 포함됩니다.
예제
다음 예제에서는 중첩 클래스를 정의합니다.
// nested_type_names1.cpp
class WinSystem
{
public:
class Window
{
public:
Window(); // Default constructor.
~Window(); // Destructor.
int NumberOf(); // Number of objects of class.
int Count(); // Count number of objects of class.
private:
static int CCount;
};
class CommPort
{
public:
CommPort(); // Default constructor.
~CommPort(); // Destructor.
int NumberOf(); // Number of objects of class.
int Count(); // Count number of objects of class.
private:
static int CCount;
};
};
// Initialize WinSystem static members.
int WinSystem::Window::CCount = 0;
int WinSystem::CommPort::CCount = 0;
int main()
{
}
중첩 클래스에 정의된 이름에 액세스하려면 범위 결정 연산자(::)를 사용하여 전체 클래스 이름을 생성합니다. 이전 예제의 정적 멤버 초기화에 이 연산자가 사용되었습니다. 프로그램에 중첩 클래스를 사용하려면 다음과 같은 코드를 사용합니다.
WinSystem::Window Desktop;
WinSystem::Window AppWindow;
cout << "Number of active windows: " << Desktop.Count() << "\n";
중첩된 익명 클래스 또는 구조체를 다음과 같이 정의할 수 있습니다.
// nested_type_names2.cpp
class Ledger
{
class
{
public:
double PayableAmt;
unsigned PayableDays;
} Payables;
class
{
public:
double RecvableAmt;
unsigned RecvableDays;
} Receivables;
};
int main()
{
}
익명 클래스는 멤버 함수와 정적 멤버가 없는 집합체여야 합니다.
END Microsoft 전용
참고
열거 형식을 클래스 선언 안에 정의할 수 있지만 그 반대는 불가능합니다. 클래스 형식을 열거형 선언 안에 정의할 수는 없습니다.