这可以用 4 个类模块模拟“覆盖函数”:Functions、IFunction、FunctionAdd、FunctionSubtract。
类模块功能:
Function aFunction(x As Integer, y As Integer) As Integer
aFunction = x + y
End Function
接口函数:
Function aFunction(x As Integer, y As Integer) As Integer
End Function
类模块函数添加:
Implements IFunctions
Private mFunctions As Functions
Private Sub Class_Initialize()
Set mFunctions = New Functions
End Sub
Private Sub Class_Terminate()
Set mFunctions = Nothing
End Sub
Private Function IFunctions_aFunction(x As Integer, y As Integer) As Integer
IFunctions_aFunction = mFunctions.aFunction(x, y) ' Uses the standard aFunction
End Function
类模块 FunctionSubtract:
Implements IFunctions
Private mFunctions As Functions
Private Sub Class_Initialize()
Set mFunctions = New Functions
End Sub
Private Sub Class_Terminate()
Set mFunctions = Nothing
End Sub
Private Function IFunctions_aFunction(x As Integer, y As Integer) As Integer
IFunctions_aFunction = x - y ' Override aFunction, subtract values
End Function
你可以用这个来测试:
Dim f As IFunctions
Set f = New FunctionAdd: Debug.Print f.aFunction(1, 2)
Set f = New FunctionSubtract: Debug.Print f.aFunction(1, 2)
当然,这对于一个功能来说是乏味的。如果您在许多类中有很多要覆盖的功能,我可能会很有用。