Visual basic 6.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如马特建议,此错误:
源于您尝试将
Foo()
的返回值分配给固定数组,而不是动态数组大批。您只需向编译器表明您声明的变量是一个数组,而不是数组的实际大小。它将根据返回的数组的大小计算出大小。此外,您应该始终为函数指定返回值类型。在 VB 中,您可以通过在函数声明末尾放置
As Type
子句来实现此目的。在本例中,您需要一个双精度数组,写为Double()
。因此,重写您的代码,使其看起来像这样,合并这两个更改:
此代码显示一个值为“1”的消息框,正如预期的那样。
As Matt suggests, this error:
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 asDouble()
.So, rewrite your code to look like this, incorporating both of those changes:
This code displays a message box with the value "1", just as expected.
您只能分配给动态数组。尝试:
You can only assign to a dynamic array. Try: