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

时间:2019-01-28 17:04:35

标签: oop ocaml

我正在尝试在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

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

1 个答案:

答案 0 :(得分:1)

最简单的解决方案可能是分解值实例的公共部分,避免使用超类的吸气剂,而只需从类参数中定义矩形即可。

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

如果您需要通过吸气剂访问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