gpt4 book ai didi

oop - 无法从另一个实例变量的定义中访问实例变量 super

转载 作者:行者123 更新时间:2023-12-04 15:49:37 25 4
gpt4 key购买 nike

我正尝试在 OCAML 中做一些 OOP。

这里有两个类:

class virtual game_object id x y z =
object (self)
val id : int = id
val x : int = x
val y : int = y
val z : int = z
method get_x = x
method get_y = y
method get_z = z
end;;
 class tile id x y z tile_type =
object(self)
inherit game_object id x y z as super
val tile_type : tile_type = tile_type
val w : int = 80
val h : int = 80
val box : Sdl.rect = Sdl.Rect.create super#get_x super#get_y w h (* This line triggers the error *)
method get_tile_type = tile_type
end
;;

当我尝试编译时,出现此错误:

The instance variable super cannot be accessed from the definition of another instance variable

我不知道如何解决这个问题。请帮忙?谢谢。

最佳答案

最简单的解决方案可能是分解值实例的公共(public)部分,避免使用父类(super class)的 getter,而只根据类参数定义矩形:

class tile id x y z tile_type =
let w = 80 in
let h = 80 in
object(self)
val box = Sdl.Rect.create x y w h
inherit game_object id x y z as super
val tile_type : tile_type = tile_type
val w = w
val h = h
method get_tile_type = tile_type
end

如果您需要通过 getter 访问 xy,您可以使 rect 可变,首先将其初始化为一个虚拟值,然后添加一个初始化程序以将其设置为正确的值:

class tile id x y z tile_type =
object(self)
inherit game_object id x y z as super
val tile_type : tile_type = tile_type
val w = 80
val h = 80
val mutable box = Sdl.Rect.create 0 0 0 0
initializer box <- Sdl.Rect.create super#get_x super#get_y w h
method get_tile_type = tile_type
end

关于oop - 无法从另一个实例变量的定义中访问实例变量 super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54406945/

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