我有一个虚拟超类和一个子类继承它。以下是我的情况的一个简单例子:
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删除subMethod时,此错误将消失。
正如您所看到的,错误消息说,其中一个问题是,我正在返回一个子类型。我不明白为什么这是一个问题,因为子继承超级。为什么它只在我添加subMethod时才出现?
发布于 2017-05-31 07:21:24
只有在添加方法子方法时才会出现错误,因为它使类子类成为类超级的子类,而在OCaml中,对象强制必须是显式的:
method virtualSuperMethod =
let newSub = new sub in
(newSub :> super)这应该能解决你的问题。
有关更多细节,您可以查看https://realworldocaml.org/v1/en/html/objects.html。
https://stackoverflow.com/questions/44276970
复制相似问题