在互联网上读到我们将FreeBASIC称为面向对象的语言,在这种语言中,可以创建原语类并将其用作真正的对象。我见过一些例子,但我不能理解它们是如何工作的,因为当我去编译时,总是会给我一些错误。
这是我的代码的一个例子,我试图理解如何使用它
type MyClass
dim mystring as string
function myfunction()as string
dim myout as string
myout = "Hello your message are: " + this.mystring
return myout
end function
end type
dim myobject as myclass
myobject.mystring = "Im noob"
print myobject.myfunction但这种方式行不通
发布于 2021-09-28 11:42:18
不幸的是,FreeBASIC有一个不优雅的类管理,并且有一些限制,当你创建一个类时,你不能把函数或subs放在里面,但是你可以声明它们,然后在类型之外构建它们,下面我写了一个源代码,它展示了它是如何构造的,当你创建一个在类内部声明的函数时,它的前面必须是用点分隔的类名
'This one define "IsEven(value)"
'that give true or 1 if the vaule n are Even number
#define IsEven(n) ((n AND 1) = 0)
'I make a class type where inside are 2 vars and 2 functions
type Useless
' this is the vars as integer
dim StartNum as integer
dim CurrentNum as integer
' this are the functions declared we ave to declare the function who work inside the class
declare function EvenValue(byval value as integer)as integer
declare function OddValue(byval value as integer)as integer
declare function FinalValue()as string
end type
' After declare the function inside the type (class) we ave to use the
' name of type followed with the name of the function separated by dot.
'
' inside type "declare myfunction()as integer"
' the function can be string too or other type
'
' when close the type with "End Type" you can make the function
' function nameclass.myfunction()as integer
function Useless.EvenValue(byval value as integer)as integer
dim Result as integer
Result = (value / 2)
return Result
end function
function Useless.OddValue(byval value as integer)as integer
dim Result as integer
Result = ((value * 3) + 1 )
return Result
end function
function Useless.FinalValue()as string
'with this you can use every function, var or sub
'inside the class(type)
'watever name you used for the object
dim OutMess as String
OutMess = "Start value =" + str(this.StartNum) + " ---- End value =" + str(this.CurrentNum)
return OutMess
end function
'this are global var outside of class(type)
dim thenexit as integer = 0
'this is the object created as class
dim Calculate as Useless
'message text and store imput inside the public integer var inside the object
print "type a number"
input Calculate.StartNum
'you can change value taked from other var from the object
Calculate.CurrentNum = Calculate.StartNum
'We use the do until cicle because we know at last we ave the one value
do until(thenexit > 0)
if IsEven(Calculate.CurrentNum) then
'we use the object.function for even value
Calculate.CurrentNum = Calculate.EvenValue(Calculate.CurrentNum)
else
'we use the object.function for odd value
Calculate.CurrentNum = Calculate.OddValue(Calculate.CurrentNum)
end if
print Calculate.CurrentNum
if Calculate.CurrentNum = 1 then
'and at the end we use the function with shared vars
print Calculate.FinalValue
thenexit = 1
end if
loophttps://stackoverflow.com/questions/69360893
复制相似问题