OCaml对象实例变量分辨率

时间:2015-11-17 18:29:23

标签: class object ocaml

我有点喜欢这个

class root = object

  val bars = "123"

end

class derived bars = object

  inherit root as super

  method speak =
    print_endline bars

end

let () =
  let a = new derived "hello" in
  a#speak

令人惊讶的是印有“123”而不是“你好”。

1)这是否意味着通过首先查看最根类来解析实例变量?

2)假设1,是否可以确保实例变量从当前类向上解析为父类? (我怀疑这是可能的,因为“它只是对象如何在OCaml中工作”)

3)是否存在编译器警告以防止,警告此

1 个答案:

答案 0 :(得分:1)

我认为这只是

的变体
let f bars =
  let bars = "123" in
  print_endline bars

第二个值bars隐藏第一个值。 inherit root展开为val bars = "123"并隐藏bars值。

您可以做什么来覆盖bars

class derived x = object
  inherit root as super
  val bars = x
  method speak =
    print_endline bars
end