Visual basic 6.0:返回数组的函数

发布于 2024-11-07 21:15:02 字数 291 浏览 0 评论 0原文

有没有比以下更好的方法创建返回数组的函数:

function foo
 Dim bar(1 to 2)as double
 bar(1)=1
 bar(2)=2
 foo=bar
end function

和 在代码中:

arrayx=foo

因为当我声明 Dim arrayx(1 to 2) as double 时,它会抛出错误“无法分配数组”当我不这样做时不声明变量 arrayx 似乎没有任何问题。

Is there better way how to create function returning array than:

function foo
 Dim bar(1 to 2)as double
 bar(1)=1
 bar(2)=2
 foo=bar
end function

and in code:

arrayx=foo

Because when I declare Dim arrayx(1 to 2) as double it throws an error "can't assign array" When I don't declare the variable arrayx it doesn't seem to have any problems.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

居里长安 2024-11-14 21:15:02

正如马特建议,此错误:

编译错误:无法分配给数组

源于您尝试将 Foo() 的返回值分配给固定数组,而不是动态数组大批。您只需向编译器表明您声明的变量是一个数组,而不是数组的实际大小。它将根据返回的数组的大小计算出大小。

此外,您应该始终为函数指定返回值类型。在 VB 中,您可以通过在函数声明末尾放置 As Type 子句来实现此目的。在本例中,您需要一个双精度数组,写为 Double()

因此,重写您的代码,使其看起来像这样,合并这两个更改:

Function Foo() As Double()      ' note the specification of a return value
   Dim bar(1 To 2) As Double
   bar(1) = 1
   bar(2) = 2
   Foo = bar
End Function

Private Sub Command1_Click()
   Dim arrayx() As Double       ' note the declaration of a DYNAMIC array
   arrayx = Foo()
   MsgBox arrayx(1)
End Sub

此代码显示一个值为“1”的消息框,正如预期的那样。

As Matt suggests, this error:

Compile error: Can't assign to array

stems from the fact that you've tried to assign the return value of Foo() to a fixed array, rather than a dynamic array. You simply need to indicate to the compiler that the variable you're declaring is an array, not the actual size of the array. It will figure out the size based on the size of the array that is returned.

Additionally, you should always specify a return value type for your functions. You do that in VB by placing an As Type clause at the end of the function declaration. In this case, you want an array of doubles, written as Double().

So, rewrite your code to look like this, incorporating both of those changes:

Function Foo() As Double()      ' note the specification of a return value
   Dim bar(1 To 2) As Double
   bar(1) = 1
   bar(2) = 2
   Foo = bar
End Function

Private Sub Command1_Click()
   Dim arrayx() As Double       ' note the declaration of a DYNAMIC array
   arrayx = Foo()
   MsgBox arrayx(1)
End Sub

This code displays a message box with the value "1", just as expected.

第七度阳光i 2024-11-14 21:15:02

您只能分配给动态数组。尝试:

Dim arrayx() as Double

You can only assign to a dynamic array. Try:

Dim arrayx() as Double
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文