1

我试图打印这个类的一个对象:

define class <bill> (<object>)
    slot num :: <string>;
    slot ref :: <string>;
end class <bill>;

我可以做一个像say

define method say (bill : <bill>) => ();
    format-out("num:%s\n", bill.num);
    format-out("ref:%s\n", bill.ref);
end method say;

但我想要一种将对象转换为<string>可以使用的方法

format-out("%s\n", bill);

or

format-out("%s\n", as(<string>, bill));

or

format-out("%=\n", bill);

我试过了

define method as(type == <string>, bill :: <bill>) 
  => (s :: <string>);
  let result :: <stretchy-vector> = make(<stretchy-vector>);
  add!(result, bill.num);
  add!(result, bill.ref);
  join(result, " ");
end method as;

但有:

format-out("\%s\n", as(<string>,bill)); 

我有这个结果

Object {<bill>} cannot be converted to class {<class>: <string>}
Object {<bill> 0x1ff8180} cannot be converted to class {class <string> 0x7f5d5c645c00}
Breaking into debugger.
Trace/breakpoint trap

一个与这个:

format-out("%s\n", bill);

结果:

{<bill> #x00000000025EF1B0}

我做错了什么?打印对象的标准(惯用)方式是什么?

4

1 回答 1

2

添加对打印对象的支持的惯用方法是专门化 print-object。但是,如果您希望能够将对象表示形式转换为字符串,则可以像您一样将其专门化为泛型。它在这里工作,所以也许某处存在错误:

module: bill

define class <bill> (<object>)
  constant slot num :: <string>, init-keyword: num:;
  constant slot ref :: <string>, init-keyword: ref:
end class <bill>;

define method as(type == <string>, bill :: <bill>) => (s :: <string>);
  join(vector(bill.num, bill.ref), " ");
end method as;

format-out("%=\n", as(<string>, make(<bill>, num: "1", ref: "a")));

结果:

$ bill 
"1 a"
于 2013-05-08T08:18:17.817 回答