VB6: How to pass temporary to a function in Visual Basic 6
In C++ it is possible to pass a temporary object argument to a function:
struct Foo
{
Foo(int arg);
// ...
}
void PrintFoo(const Foo& f);
PrintFoo(Foo(10))
I am trying to implement something similar in Visual Basic 6:
'# Scroll bar params
Public Type ScrollParam开发者_开发知识库s
sbPos As Long
sbMin As Long
sbMax As Long
End Type
Public Function MakeScrollParams(pos As Long, min As Long, max As Long)
Dim params As ScrollParams
With params
.sbPos = pos
.sbMin = min
.sbMax = max
End With
Set MakeScrollParams = params
End Function
'# Set Scroll bar parameters
Public Sub SetScrollParams(sbType As Long, sbParams As ScrollParams)
Dim hWnd As Long
' ...
End Sub
However, Call SetScrollParams(sbHorizontal, MakeScrollParams(3, 0, 10))
raises an error: ByRef argument type mismatch. Why?
A couple of things need to change from your existing code:
You need to strongly-type the declaration of the
MakeScrollParams
function.It returns an instance of the
ScrollParams
type, so you should specify that explicitly in the declaration. Like so:Public Function MakeScrollParams(pos As Long, min As Long, max As Long) As ScrollParams
You need to remove the
Set
keyword from the last line in that function in order to avoid an "Object Required" compilation error. You can only useSet
with objects, such as instances of classes. For regular value types, you omit it altogether:MakeScrollParams = params
So the full function declaration would look like this:
Public Function MakeScrollParams(pos As Long, min As Long, max As Long) As ScrollParams
Dim params As ScrollParams
With params
.sbPos = pos
.sbMin = min
.sbMax = max
End With
MakeScrollParams = params
End Function
And calling it like this:
Call SetScrollParams(sbHorizontal, MakeScrollParams(3, 0, 10))
now works perfectly.
Maybe?
Public Function MakeScrollParams(pos As Long, min As Long, max As Long) As ScrollParams
精彩评论