2013-02-23 61 views
0
Public Class Population 

Dim tours() As Tour ' Tour is a class and I have to make and object array 

Public Sub New(ByVal populationSize As Integer, ByVal initialise As Boolean) 

    Dim tours As New Tour(populationSize) ' 

    If initialise Then 
     ' Loop and create individuals 
     For i As Integer = 0 To (populationSize - 1) 
      Dim newTour As New Tour() 
      newTour.generateIndividual() 
      saveTour(i, newTour) 
     Next i 
    End If 
End Sub 

Public Sub saveTour(ByVal index As Integer, ByVal tour As Tour) 
    tours(index) = tour   ' getting error in this line 
End Sub 
在Java

相同的代碼是this link未將對象引用設置爲對象的實例。 Visual Basic中的VB

+1

請注意,您的數組的大小將是族羣大小+ 1,因爲在VB中的數組聲明傳遞的值是上限,不尺寸。 – 2013-02-25 16:30:48

回答

2

它已經有一段時間,我已經做了VB,但我認爲你​​語句來在New - 方法創建一個新的局部變量tours隱藏的全局變量tours

試試這個:

Public Class Population 

Dim tours() As Tour 

Public Sub New(ByVal populationSize As Integer, ByVal initialise As Boolean) 

    tours = New Tour(populationSize) ' 

    If initialise Then 
     ' Loop and create individuals 
     For i As Integer = 0 To (populationSize - 1) 
      Dim newTour As New Tour() 
      newTour.generateIndividual() 
      saveTour(i, newTour) 
     Next i 
    End If 
End Sub 

Public Sub saveTour(ByVal index As Integer, ByVal tour As Tour) 
    tours(index) = tour 
End Sub 
1

嘗試,

Public Sub New(ByVal populationSize As Integer, ByVal initialise As Boolean) 

    ReDim tours(populationSize) 

    If initialise Then 
     ' Loop and create individuals 
     For i As Integer = 0 To (populationSize - 1) 
      Dim newTour As New Tour() 
      newTour.generateIndividual() 
      saveTour(i, newTour) 
     Next i 
    End If 
End Sub 
相關問題