gpt4 book ai didi

lisp - CLOS 中的构造函数等价于什么?

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:48 26 4
gpt4 key购买 nike

你会如何用 Lisp 表达下面的 Java 代码?

class Foo {
private String s;

public Foo(String s) {
this.s = s;
}
}

class Bar extends Foo {
public Bar(int i) {
super(Integer.toString(i));
}
}

在 Lisp 中,make-instanceinitialize-instance 是否等同于构造函数?如果是,您如何调用父类(super class)构造函数?

最佳答案

在方法中使用 CALL-NEXT-METHOD 调用下一个方法。

通常只需使用标准方法组合工具并为 INITIALIZE- 编写 :BEFORE:AFTER:AROUND 方法-实例

一种方式:

(defclass foo ()
((s :type string :initarg :s)))

(defclass bar (foo) ())

(defmethod initialize-instance :around ((b bar) &key i)
(call-next-method b :s (princ-to-string i)))

例子:

CL-USER 17 > (make-instance 'bar :i 10)
#<BAR 402000B95B>

CL-USER 18 > (describe *)

#<BAR 4130439703> is a BAR
S "10"

请注意,我调用了 CALL-NEXT-METHOD,但没有更改它分派(dispatch)的参数。我刚刚更改了 &key initarg 参数。

关于lisp - CLOS 中的构造函数等价于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16089809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com