【问题标题】:VB6: How to pass temporary to a function in Visual Basic 6VB6:如何将临时传递给 Visual Basic 6 中的函数
【发布时间】:2011-05-25 10:26:07
【问题描述】:

在 C++ 中,可以将临时对象参数传递给函数:

struct Foo
{
    Foo(int arg);
    // ...
}

void PrintFoo(const Foo& f);

PrintFoo(Foo(10))

我正在尝试在 Visual Basic 6 中实现类似的功能:

'# Scroll bar params
Public Type ScrollParams
    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

但是,Call SetScrollParams(sbHorizontal, MakeScrollParams(3, 0, 10)) 会引发错误:ByRef 参数类型不匹配。为什么?

【问题讨论】:

  • 公共函数 MakeScrollParams(pos As Long, min As Long, max As Long) 不应该是:Public Function MakeScrollParams(pos As Long, min As Long, max As Long) As ScrollParams?跨度>
  • 没错!我忘了在函数声明后输入As ScrollParams。谢谢!

标签: vb6


【解决方案1】:

您现有的代码需要做一些改变:

  1. 您需要强类型化MakeScrollParams 函数的声明。

    它返回ScrollParams 类型的实例,因此您应该在声明中明确指定它。像这样:

    Public Function MakeScrollParams(pos As Long, min As Long, max As Long) As ScrollParams
    
  2. 您需要从该函数的最后一行删除Set 关键字,以避免“需要对象”编译错误。您只能将Set 与对象一起使用,例如类的实例。对于常规值类型,您可以完全省略它:

    MakeScrollParams = params
    


所以完整的函数声明如下所示:

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

然后这样称呼它:

Call SetScrollParams(sbHorizontal, MakeScrollParams(3, 0, 10))

现在完美运行。

【讨论】:

    【解决方案2】:

    也许?

    公共函数 MakeScrollParams(pos As Long, min As Long, max As Long) As ScrollParams

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 2018-12-20
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多