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

标签 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

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

最佳答案

最简单的解决方案可能是分解值实例的公共(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/

相关文章:

Javascript new 关键字不重置所有属性

data-structures - 左堆二版创建实现

linux - 如何使 OCaml 可以使用从 OPAM 安装的库?

c++ - 在 C++ 中类继承的情况下强制后期方法解析

php - 仅声明一次 Use "Namespace"初始化并且所有文件都为对象获得相同的命名空间

java - Java 中的 OOP : Class inheritance with method chaining

ocaml - 在 OCamlyacc 中使用外部类型声明

php - PHP OOP更新记录,但显示错误消息

f# - F# 中的命令式多态性

arrays - 确定2个对应集合的类型