【问题标题】:Use superclass constructor?使用超类构造函数?
【发布时间】:2015-05-24 08:06:23
【问题描述】:

所以我有课

(defclass foo ()
  ((a :initarg :a :accessor a)
   (b :initarg :b :accessor b)))

(defclass bar (foo)
  ((c :initarg :c)))

还有一个构造函数

(defun make-foo (a b)
  (make-instance 'foo :a a :b b))

有没有一种简单的方法来定义一个函数,该函数接受现有的FOO 并生成一个BAR 并定义了额外的插槽C? IE。无需列出所有插槽:

(defun make-bar-from-foo (existing-foo c)
  (make-instance 'bar :a (a existing-foo) :b (b existing-foo) :c c))

【问题讨论】:

  • 没有内置任何东西。您确定不想只使用CHANGE-CLASSexisting-foo 更改为bar
  • @Barmar 哦不知道CHANGE-CLASS,谢谢!
  • CLOS 本身没有构造函数。如果你想要的是一个新的 bar 对象,change-class 可能不是你想要的,因为它实际上改变了对象。
  • @Barmar 你们想提交这个作为答案吗?谢谢
  • 嗯,这取决于您真正需要完成的工作。正如@Vatine 所说,如果您使用CHANGE-CLASS,您不会得到新对象,它会修改原始对象。您可以复制foo,然后更改其类,但 CLOS 没有内置的复制操作,因此您必须对其进行编码(它类似于 make-bar-from-foo,只是它不会' t 添加c 槽。

标签: common-lisp clos


【解决方案1】:

这可能是一个选项:

(defclass foo ()
  ((a :initarg :a :accessor a)
   (b :initarg :b :accessor b)
   (initargs :accessor initargs))) ;Remember the initargs here.

(defclass bar (foo)
  ((c :initarg :c :accessor c)))

(defmethod initialize-instance :after ((foo foo) &rest initargs)
  (setf (initargs foo) initargs))

(defun make-bar-from-foo (foo c)
  (apply #'make-instance 'bar :c c (initargs foo))) ;And use them here.

【讨论】:

    猜你喜欢
    • 2010-09-29
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多