gpt4 book ai didi

oop - 在 OCaml 中即时创建对象

转载 作者:行者123 更新时间:2023-12-01 01:38:09 24 4
gpt4 key购买 nike

我试图通过使用编译代码而不是顶层来学习 OCaml;然而,网上的许多示例代码似乎对后者有吸引力。

我想在下面的对象方法中创建一个新的 Foo 。此代码无法编译,引用 doFooProc 定义的语法错误。

class bar =
object (self)
method doFooProc = (new Foo "test")#process
end;;

class foo (param1:string)=
object (self)
method process = Printf.printf "%s\n" "Processing!"
initializer Printf.printf "Initializing with param = %s\n" param1
end;;

此外,“let”语法在类定义中似乎并不友好。这是为什么?
class bar =
object (self)
method doFooProc =
let xxx = (new Foo "test");
xxx#process
end;;

class foo (param1:string)=
object (self)
method process = Printf.printf "%s\n" "Processing!"
initializer Printf.printf "Initializing with param = %s\n" param1
end;;

如何在 doFooProc 方法中创建 foo 类的新对象并调用实例化的 foo 的 process 命令?

最佳答案

对于两个相互递归的类,使用 and 关键字

class bar =
object (self)
method doFooProc =
let xxx = (new foo "test") in
xxx#process
end
and foo (param1:string)=
object (self)
method process = Printf.printf "%s\n" "Processing!"
initializer Printf.printf "Initializing with param = %s\n" param1
method bar = new bar
end;;`

关于oop - 在 OCaml 中即时创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/512157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com