** 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 类生成器