구조체 및 기타 프로그래밍 요소(Visual Basic)

구조체는 배열, 개체, 프로시저, 다른 구조체와 함께 사용할 수 있습니다. 상호 작용은 이러한 요소들이 개별적으로 사용하는 것과 같은 구문을 사용합니다.

참고 항목

구조체 선언에서는 구조체 요소를 초기화할 수 없습니다. 구조체 형식으로 선언한 변수 요소에만 값을 할당할 수 있습니다.

구조체와 배열

구조체에는 배열이 하나 이상 구조체 요소로 있을 수 있습니다. 다음 예제에서는 이것을 보여 줍니다.

Public Structure systemInfo  
    Public cPU As String  
    Public memory As Long  
    Public diskDrives() As String  
    Public purchaseDate As Date  
End Structure

개체 속성에 액세스하는 것과 같은 방식으로 구조체에서 배열 값에 액세스합니다. 다음 예제에서는 이것을 보여 줍니다.

Dim mySystem As systemInfo  
ReDim mySystem.diskDrives(3)  
mySystem.diskDrives(0) = "1.44 MB"  

구조체의 배열을 선언할 수도 있습니다. 다음 예제에서는 이것을 보여 줍니다.

Dim allSystems(100) As systemInfo  

동일한 규칙을 따라 이 데이터 아키텍처의 구성 요소에 액세스합니다. 다음 예제에서는 이것을 보여 줍니다.

ReDim allSystems(5).diskDrives(3)  
allSystems(5).CPU = "386SX"  
allSystems(5).diskDrives(2) = "100M SCSI"  

구조체와 개체

구조체에는 개체가 하나 이상 구조체 요소로 있을 수 있습니다. 다음 예제에서는 이것을 보여 줍니다.

Protected Structure userInput  
    Public userName As String  
    Public inputForm As System.Windows.Forms.Form  
    Public userFileNumber As Integer  
End Structure  

이 선언에서는 Object보다는 특정 개체 클래스를 사용해야 합니다.

구조체와 프로시저

구조체를 프로시저 인수로 전달할 수 있습니다. 다음 예제에서는 이것을 보여 줍니다.

Public currentCPUName As String = "700MHz Pentium compatible"  
Public currentMemorySize As Long = 256  
Public Sub fillSystem(ByRef someSystem As systemInfo)  
    someSystem.cPU = currentCPUName  
    someSystem.memory = currentMemorySize  
    someSystem.purchaseDate = Now  
End Sub  

앞의 예제에서는 호출 코드에 변경 사항이 적용되도록 프로시저가 그 요소를 수정하게 만드는 참조를 통해 구조체를 전달합니다. 구조체가 변경되지 않게 하려면 해당 구조체를 값으로 전달합니다.

Function 프로시저에서도 구조체를 반환할 수 있습니다. 다음 예제에서는 이것을 보여 줍니다.

Dim allSystems(100) As systemInfo  
Function findByDate(ByVal searchDate As Date) As systemInfo  
    Dim i As Integer  
    For i = 1 To 100  
        If allSystems(i).purchaseDate = searchDate Then Return allSystems(i)  
    Next i  
   ' Process error: system with desired purchase date not found.  
End Function  

구조체 안의 구조체

구조체는 다른 구조체를 포함할 수 있습니다. 다음 예제에서는 이것을 보여 줍니다.

Public Structure driveInfo  
    Public type As String  
    Public size As Long  
End Structure  
Public Structure systemInfo  
    Public cPU As String  
    Public memory As Long  
    Public diskDrives() As driveInfo  
    Public purchaseDate As Date  
End Structure  
Dim allSystems(100) As systemInfo  
ReDim allSystems(1).diskDrives(3)  
allSystems(1).diskDrives(0).type = "Floppy"  

이 기술을 사용하여 한 모듈에서 정의한 구조체를 다른 모듈에서 정의한 구조체 안에 캡슐화할 수 있습니다.

구조체는 임의의 깊이까지 다른 구조체를 포함할 수 있습니다.

참고 항목