VB6中的面向对象编程---实现类继承
确切地说VB6不能实现真正意义上的类继承(如C++中的继承),但是通过其关键字Implements也提供了类似的功能。
我们先建一个类模块CBase.cls
代码如下:
Private mvarBaseProperty As String
Public Sub BaseFunction()
MsgBox “Hello world!”
End Sub
Public Property Let BaseProperty(ByVal VData As String)
mvarBaseProperty = VData
End Property
Public Property Get BaseProperty() As String
BaseProperty = mvarBaseProperty
End Property
接下来我们新建一类模块(Cinherit.cls),代码如下,其间有关键的注释
Implements CBase '注意此关键字
Dim m_BaseProperty As String
'---------------------------------------------------------------------
'虚线间的代码即是从CBase类继承的.
'注意其格式如下:基类_属性名(或方法名)
'其方法的声明关键字public也变为了private
Private Property Get CBase_BaseProperty() As String
BaseProperty = m_BaseProperty
End Property
Private Property Let CBase_BaseProperty(ByVal VData As String)
m_BaseProperty = VData
End Property
Private Sub CBase_BaseFunction()
MsgBox "Inherit"
End Sub
'---------------------------------------------------------------------
'此方法是继承类自己的方法
Public Sub InheritMsg()
MsgBox "my owner msg"
End Sub
现在我们新建一窗体来做测试,我们把测试代码放在Form_Load事件中
测试一:
Dim objTest As CBase
Set objTest = New CBase
With objTest
.BaseFunction
End With
Set objTest = Nothing
运行程序,弹出base,说明是调用Cbse中的BaseFunction函数
测试二:
Dim objTest As CBase
Set objTest = New CInherit
With objTest
.BaseFunction
End With
Set objTest = Nothing
运行程序,弹出Inherit,说明是调用Cinherit中的Base函数
测试三:
Dim objTest As CInherit
Set objTest = New CInherit
With objTest
.InheritMsg
End With
Set objTest = Nothing
运行程序,弹出my owner function,说明继承的类可以使用自己的函数或属性.
如果您觉得自己写Cinherit类比较麻烦,您可以用vs6自带的工具Microsoft visual modeler来创建.Cbase类可以通过类生成器生成,其位置在 工程->添加类模块 ->vb类生成器