4

我正在尝试掌握 OCaml 语言语法,但在应用一些 OOP 结构时遇到了一些麻烦。我使用以下代码的目标是拥有一个继承自虚拟类 foo 的类 bar。虚拟类包含三个虚拟方法,我希望将“玩家”对象的实例作为参数。当我编译下面的代码时,我得到了错误:方法 doThis 有类型 'a -> 'b 但应该有类型 player 。这是什么意思(记住,我是新手),我该如何纠正它?

谢谢!

class player =
object

end;;

class virtual foo =
object (self)
 method virtual doThis : player
 method virtual doThat : player
 method virtual notifyAll : player array
end;;

class bar (playersIn: player array) =
object (self)
 inherit foo
 method doThis (p:player) = Printf.printf "%s\n" "This!"
 method doThat (p:player) = Printf.printf "%s\n" "That!"
 method notifyAll (p:player array) = Printf.printf "%s\n" "Notifying!"
end;;
4

2 回答 2

2

(我不知道 OCaml,但我知道 F#,它们很相似,所以希望我猜对了。)

尝试改变

method virtual doThis : player 
method virtual doThat : player 
method virtual notifyAll : player array

method virtual doThis : player -> unit
method virtual doThat : player -> unit
method virtual notifyAll : player array -> unit
于 2009-02-01T22:33:55.027 回答
1

I believe the previous answer to this is correct: the methods in question need their types to be functions that return unit.

Another, more general piece of advice: don't start learning OCaml by starting to learn the object system. Objects in OCaml can be useful, but the cases where you really want to be programming with objects are few and far between. And you won't be able to understand OCaml's object system until you get a good grip on the core language. Focus on how to solve your problems using basic algebraic datatypes (variants, tuples, records), ordinary parametric polymorphism (as opposed to the subtyping you see with polymorphic variants and objects), and modules (but not functors).

Get an understanding of these basic tools before playing around with objects. Most problems you would solve with objects in other languages are solved best in OCaml without them.

于 2009-02-08T14:42:09.453 回答