如何继承 OCaml 中的属性?

How to inherit an attribute in OCaml?

Real World OCaml 一书在其 Chapter 12 中展示了如何继承超类的方法,例如下面的方法 push

class double_stack init = object
  inherit [int] stack init as super

  method push hd =
    super#push (hd * 2)
end ;;

但是它提到 super 不像 Java 那样工作:

The preceding as super statement creates a special object called super which can be used to call superclass methods. Note that super is not a real object and can only be used to call methods.

那我如何继承父类的属性呢?

您可以访问继承的 classes 的属性,就好像它们是在当前 class 中定义的一样,与许多其他面向对象的语言非常相似;访问规则对应于 C++ 中的 protected 级别:您不能直接从 class 外部访问属性,继承 class 除外。

书中给出的特殊规定是说明class的方法不能returnsuper,因为这个符号只是访问继承方法的句法设备。当这些方法被当前 class 或另一个继承的 class.

覆盖时,此设备可能很有用
class foo = object
  val mutable v = "hello"
  method m = v
end

访问继承属性:

class bar = object
  val w = "world"
  method! m = v ^ " " ^ w 
end

注意上面的barclass覆盖了方法m,也就是说从bar内部访问foo的方法(在这个例如,当然,这不是必需的)将需要将其限定为 super#m

非法使用超级class名称:

class wrong = object(self)
  inherit foo as super
  method w = super (* cannot compile *)
end

Error: Ancestor names can only be used to select inherited methods

实现这种语义的正确方法是 return self casted 作为它的 superclass:

class correct = object(self)
  inherit foo as super
  method w = (self :> foo)  
end