2016-08-08 39 views
0

我有類此層次結構,其定義如下通過「屬性get」在父類傳遞類對象不影響嵌套類對象

cQuestion:

Private pText As String 

Private Sub Class_Initialize() 
pText = "" 
End Sub 

Property Let Text(T As String) 
    pText = T 
End Property 

Property Get Text() As String 
    Text = pText 
End Property 

cQuestionList:

Private pQList() As New cQuestion 
Private pListLen As Integer 

Private Sub Class_Initialize() 
    pListLen = 0 
End Sub 

Public Sub AddEnd(Q As String) 
    pListLen = pListLen + 1 
    ReDim Preserve pQList(1 To pListLen) 
    pQList(pListLen).Text = Q 
End Sub 

Public Function Format() As String 
    Dim i As Integer 
    If pListLen = 0 Then 
     FormatList = "There are no questions in this category" + vbNewLine 
    Else 
     FormatList = "Questions:" + vbNewLine 
     For i = 1 To pListLen 
      FormatList = FormatList + "• " + pQList(i).Text + vbNewLine 
     Next i 
    End If 
End Function 

cCategory:

Private pName As String 
Private pQList As New cQuestionList 

Private Sub Class_Initialize() 
    pName = "" 
End Sub 

Property Get QuestionList() As cQuestionList 
    Set QuestionList = pQList 
End Property 

Property Let Name(N As String) 
    pName = N 
End Property 

Property Get Name() As String 
    Name = pName 
End Property 

當我嘗試呼叫Category.QuestionList.AddEnd "Question Here", 時,它不會引發任何錯誤。但是,當我隨後致電MsgBox Category.QuestionList.Format時,我收到一個空白消息框。我不知道這是如何結束的空白,因爲格式應該總是返回文本。我在這裏做錯了什麼?我看過其他的例子,讓我們通過父類來傳遞類對象,並且看不到我在做什麼是不同的。有什麼建議麼?

示例代碼:

Dim C as New cCategory 
C.QuestionList.AddEnd "A Question" 
C.QuestionList.AddEnd "Another Question" 
MsgBox C.QuestionList.Format 

回答

2

Option Explicit在每個模塊的頂部,你會看到立即的問題:

Public Function Format() As String 
    Dim i As Integer 
    If pListLen = 0 Then 
     FormatList = "There are no questions in this category" + vbNewLine 
      '^^^^ Variable not defined. 
    Else 
     FormatList = "Questions:" + vbNewLine 
     For i = 1 To pListLen 
      FormatList = FormatList + "• " + pQList(i).Text + vbNewLine 
     Next i 
    End If 
End Function 

你要麼需要改變Public Function Format() As StringPublic Function FormatList() As String或改變FormatList分配到Format

我會親自去FormatList命名,以避免與Format功能發生衝突。