Ошибка в коде из лекций о программировании ОО в Ocaml - PullRequest
0 голосов
/ 20 июня 2019

Я искал код из лекций о ОО-программировании в ocaml. Это был приведенный код, но он не сработает, когда я его скомпилирую. Я не могу понять, почему.

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 голосов
/ 20 июня 2019

Вы создаете многословную точку, поэтому ее метод self#to_string происходит от verbose_point.В этом суть позднего связывания.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...