Классы с наследованием в FreeBasic (компилятор 0.24)
На одном простом примере показаны четыре новые ключевые команды.
Автор: fxm
Code
Type animal Extends Object ' 'Extends' to activate RTTI by inheritance of the predefined Object type
Declare Constructor (Byref _name As String = "")
Declare Function ObjectHierarchy () As String
Declare Function ObjectType () As String
Dim name As String
End Type
Constructor animal (Byref _name As String = "")
This.name = _name
End Constructor
Function animal.ObjectHierarchy () As String
Return "Object(forRTTI) <- animal"
End Function
Type dog Extends animal ' 'Extends' to inherit of animal
Declare Constructor (Byref _name As String = "")
Declare Function ObjectHierarchy () As String
End Type ' derived type may be member data empty
Constructor dog (Byref _name As String = "")
Base(_name) ' 'Base()' allows to call parent constructor
End Constructor
Function dog.ObjectHierarchy () As String
Return Base.ObjectHierarchy & " <- dog" ' 'Base.' allows to access to parent member function
End Function
Type cat Extends animal ' 'Extends' to inherit of animal
Declare Constructor (Byref _name As String = "")
Declare Function ObjectHierarchy () As String
End Type ' derived type may be member data empty
Constructor cat (Byref _name As String = "")
Base(_name) ' 'Base()' allows to call parent constructor
End Constructor
Function cat.ObjectHierarchy () As String
Return Base.ObjectHierarchy & " <- cat" ' 'Base.' allows to access to parent member function
End Function
Function animal.ObjectType () As String ' must be put after definition of dog type and cat type
If This Is dog Then ' 'Is' allows to check compatibility with type symbol
Return "dog"
Elseif This Is cat Then ' 'Is' allows to check compatibility with type symbol
Return "cat"
Else
Return "animal"
End If
End Function
Print "Name:", "Object:", "Hierarchy:"
Dim a As animal = animal("Mouse")
Print " " & a.name, " " & a.ObjectType, " " & a.ObjectHierarchy
Dim d As dog = dog("Buddy")
Print " " & d.name, " " & d.ObjectType, " " & d.ObjectHierarchy
Dim c As cat = cat("Tiger")
Print " " & c.name, " " & c.ObjectType, " " & c.ObjectHierarchy
Sleep
Результат: