2

如何在一个类中初始化一个数组属性?如何在下面初始化array1:

class Class1
    private count
    private array1

    private sub class_initialize
        count     = 0
        array1(0) = 0 'initialize first element
    end sub

end class

导致错误:Microsoft VBScript 运行时错误“800a000d”类型不匹配:“array1”

4

2 回答 2

1

我想到了:

class Class1
    private count
    private array1

    private sub class_initialize
        count  = 0
        array1 = array() 'initialize array property
    end sub

    'to add a new element to array property
    public sub add(input)
        redim preserve array1(count + 1)
        array1(count) = input
        count = count + 1
    end sub
end class
于 2013-04-28T02:45:19.697 回答
1

因为reformed 的类不能正常工作并且ShadowWizards 的评论很危险:

Option Explicit

class ArrMemberA
    private count
    private array1

    private sub class_initialize
        count  = 0
        array1 = array() 'initialize array property
    end sub

    'to add a new element to array property
    public sub add(input)
        redim preserve array1(count + 1)
        array1(count) = input
        count = count + 1
    end sub

    Public Function toString()
      toString = "[" & Join(array1, "*") & "]"
    End Function
end class

Class ArrMemberB
  Private m_a
  Private Sub Class_Initialize
    m_a = Array() ' initialize to empty dynamic array
  End Sub
  Public Sub add(input)
    ReDim Preserve m_a(UBound(m_a) + 1)
    m_a(UBound(m_a)) = input
  End Sub
  Public Function toString()
    toString = "[" & Join(m_a, "*") & "]"
  End Function
End Class

Class ArrMemberC
  Private m_a()
  Public Sub add(input)
    ReDim Preserve m_a(UBound(m_a) + 1)
    m_a(UBound(m_a)) = input
  End Sub
  Public Function toString()
    toString = "[" & Join(m_a, "*") & "]"
  End Function
End Class

Class ArrMemberD
  Private m_a()
  Private m_n
  Private Sub Class_Initialize
    m_n = -1 ' initialize to empty ubound
  End Sub
  Public Sub add(input)
    m_n = m_n + 1
    ReDim Preserve m_a(m_n)
    m_a(m_n) = input
  End Sub
  Public Function toString()
    toString = "[" & Join(m_a, "*") & "]"
  End Function
End Class

Dim a : Set a = New ArrMemberA
a.add "zero"
a.add "one"
WScript.Echo "a:", a.toString(), "- spurious empty tail element"

Dim b : Set b = New ArrMemberB
b.add "zero"
b.add "one"
WScript.Echo "b:", b.toString()

Dim c : Set c = New ArrMemberC
On Error Resume Next
 c.add "zero"
 WScript.Echo "c:", Err.Description, "- Ubound() fails for the abomination created by 'Private m_a()'"
On Error GoTo 0

Dim d : Set d = New ArrMemberD
d.add "zero"
d.add "one"
WScript.Echo "d:", d.toString()

输出:

cscript demoarray.vbs
a: [zero*one*] - spurious empty tail element
b: [zero*one]
c: Subscript out of range - Ubound() fails for the abomination created by 'Private m_a()'
d: [zero*one]

(a) 表明自己掷牌是有风险的;(b) 按我的方式行事;(c) 证明“Dim/Private/Public varname()”的结果不能是 UBound();(d) 证明“要使其工作”,您需要您试图避免的 Class_Initialize 子。

于 2013-08-08T18:57:38.357 回答