Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ocaml 虚拟类的继承-第二个对象类型没有方法x_Ocaml - Fatal编程技术网

Ocaml 虚拟类的继承-第二个对象类型没有方法x

Ocaml 虚拟类的继承-第二个对象类型没有方法x,ocaml,Ocaml,我有一个虚拟的超类和一个子类继承自它。下面是一个简单的例子: class virtual super = object(self) method virtual virtualSuperMethod : super end;; class sub = object(self) inherit super method subMethod y = y+2; method virtualSuperMethod = let newSub = new sub in

我有一个虚拟的超类和一个子类继承自它。下面是一个简单的例子:

class virtual super = object(self)

 method virtual virtualSuperMethod : super

end;;

class sub = object(self)
  inherit super

  method subMethod y =
    y+2;

  method virtualSuperMethod =
    let newSub = new sub in
    newSub

end;;
但是,当我尝试编译时,会出现以下错误:

Error: The expression "new sub" has type sub but is used with type super
       The second object type has no method subMethod
删除子方法时,此错误消失


正如您所看到的,错误消息说问题之一是我返回了一个子类型。我不明白为什么这是个问题,因为sub继承了super。为什么只有在添加子方法时才会出现错误?

只有在添加方法子方法时才会出现错误,因为它会 sub类是super类的子类,在OCaml中,对象强制必须是显式的:

method virtualSuperMethod =
let newSub = new sub in
(newSub :> super)
这会解决你的问题


您可以查看更多详细信息。

OCaml在类型之间没有隐式强制-您必须插入显式强制,如下所示:

class virtual super = object (self)
 method virtual virtualSuperMethod : super
end

class sub = object (self)
  inherit super
  method subMethod y = y + 2
  method virtualSuperMethod =
    let newSub = new sub in
    (newSub :> super)
end

同时:)如果您的目的是专门复制对象,则可以使用Oo.copy函数。不幸的是,我不熟悉Ocaml的对象部分,但您可以查看以下内容以了解更高级的用法: