有关Ocaml中OO编程的讲座中的代码错误

时间:2019-06-20 16:21:49

标签: ocaml

我正在看有关ocaml中OO编程的讲座中的一些代码。 这是给出的代码,但是当我编译它时不会起作用。我不知道为什么。

class point (x_init,y_init) = 
    object (self)
    val mutable x = x_init 
    val mutable y = y_init
     method get_x = x
     method get_y = y
     method moveto (a,b) = x <- a ; y <- b
     method rmoveto (dx,dy) = x <- x + dx ; y <- y + dy
     method to_string () = "(" ^ (string_of_int x) ^ "," ^ (string_of_int y) ^ ")"
    method distance () = sqrt (float(x*x + y*y))
     initializer Printf.printf ">> Creation of point: %s\n" (self#to_string ());
     end ;;
class verbose_point p =
     object (self) 
    inherit point p as super
    method to_string () = "point=" ^ (super#to_string ()) ^ ",distance=" ^ string_of_float (super#distance ())
          initializer Printf.printf ">> Creation of verbose point: %s\n" (self#to_string ())
                end ;; 

这是预期的结果:

new verbose_point (1,1);;
>> Creation of point: (1,1)
>> Creation of verbose point: point=(1,1), distance=1.414213- : verbose_point = <obj>

但是我却收到了:

new verbose_point (1,1);;
>> Creation of point: (1,1), distance=1.414213
>> Creation of verbose point: point=(1,1), distance=1.414213- : verbose_point = <obj>

1 个答案:

答案 0 :(得分:0)

您创建了一个详细点,因此其self#to_string方法来自verbose_point。这是后期绑定的本质。